How to "clear" a string in PHP using regex?

For example, suppose I have

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

I want to filter a string so that only letters, numbers and "." remain inferior to "C.a534"

How to do it?

+3
source share
5 answers

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

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

Please note that I use a modifier ifor regular expression. It is case insensitive, so we do not need to specify a-zand a-z.

+9
source

answered many times, but:

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


$blah = cleanit("C$#@#.a534&");
+4
source

preg_replace

$text = preg_replace('/[' . preg_quote('CHARSYOUDONTWANT','/') .  ']/','',$text);

, ,

$text = preg_replace('/[^' . preg_quote('CHARSONLYYOUWANT','/') .  ']/','',$text);

$blah = "C$#@#.a534&";
$blah = preg_replace('/[' . preg_quote('$#@&','/') . ']/','',$blah);
echo $blah;
+2

:

$text = preg_replace('/[^a-zA-Z0-9.]/','',$text);
+1

http://php.net/manual/en/function.preg-replace.php

Replace all invalid characters with an empty string.

0
source

All Articles