Search code examples
phpregexstrip

PHP make a string a valid php variable


I read the PHP Variable page and it states the correct way to assign a variable is. [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

so it is a valid variable thats the official expression.

my question is how can I make a string

$string = "not a valid php var, and @ or # or are not allowed";
process_string($string);//should return "notavalidphpvarandororarenotallowed"

so all I am asking is to strip off any characters that do not meet the condition on the regex above.


Solution

  • $str = preg_replace("/[^a-zA-Z_\x7f-\xff]/", "", $str);