Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a regex in PHP to remove special characters?

Tags:

regex

php

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 "_"

like image 749
Ben McRae Avatar asked Apr 13 '09 20:04

Ben McRae


1 Answers

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

This should do the trick.

like image 116
runfalk Avatar answered Oct 20 '22 03:10

runfalk