Php – How to write a regex in PHP to remove special characters

phpregex

I'm pretty new to PHP, and I noticed there are many different ways of handling regular expressions.

This is what I'm currently using:

$replace = array(" ",".",",","'","@");
$newString = str_replace($replace,"_",$join);

$join = "the original string i'm parsing through";

I want to remove everything which isn't a-z, A-Z, or 0-9. I'm looking for a reverse function of the above. A pseudocode way to write it would be

If characters in $join are not equal to a-z,A-Z,0-9
then change characters in $join to "_"

Best Solution

$newString = preg_replace('/[^a-z0-9]/i', '_', $join);

This should do the trick.