php - removing characters from string if it's not in the regex
211
basically i want to remove unwanted characters from string - i have a list of valid characters in a regex or map ( or whatever that is )
$permitted_uri_chars = ' ) ( ( ) a-z 0-9~%.+:_\- δ ο κ ι μ ή χ ό ν';
right now i'm using this code which seems slow and messy and above all i have to write every single character ( i cant do a-z 0-9 )
$string = "this is a test";
$permitted_uri_chars = ' ) ( ( ) a b c d e z 0 1 2 3 4 9 _ - δ ο κ ι μ ή χ ό ν';
$permitted_uri_chars = explode(' ' , $permitted_uri_chars );
$unwanted = array();
for($i = 0 ; $i < strlen($string) ; $i++)
{
if(!in_array($string[$i] , $permitted_uri_chars ))
$unwanted[] = $string[$i] ;
}
$string = str_replace($unwanted, '-' , $string);
echo $string;
Answer
Solution:
is probably the best tool for the job:
Answer
Solution:
Use
here instead, using a negated character class.
Note: Not clear if parentheses are permitted, but you can remove them if you need to. I included them since you have multiple in
$permitted_uri_chars
.