Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I "clean" a String in PHP using regex?

Tags:

regex

php

For example suppose I have

$blah = "C$#@#.a534&";

I wish to filter the string so that only letters, numbers and "." remain yielding "C.a534"

How do I do this?

like image 285
deltanovember Avatar asked Dec 02 '22 02:12

deltanovember


2 Answers

If you know what characters should be allowed, you can use a negated character group (in a regular expression) to remove everything else:

$blah = preg_replace('/[^a-z0-9\.]/i', '', $blah);

Note that i am using the i modifier for the regular expression. It matches case-insensitive, so that we do not need to specify a-z and A-Z.

like image 96
jwueller Avatar answered Dec 03 '22 14:12

jwueller


been answered lots of times but:

function cleanit($input){
    return preg_replace('/[^a-zA-Z0-9.]/s', '', $input);
}


$blah = cleanit("C$#@#.a534&");
like image 41
Lawrence Cherone Avatar answered Dec 03 '22 15:12

Lawrence Cherone