Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to remove anything but alphanumeric & spaces (in PHP)

Tags:

regex

php

I'm trying to remove, via regular expression, all but alphanumeric characters & spaces.

Here's the conversion I am hoping to achieve.

"I am a string" → "I am a string"
"How are you?" → "How are you"
"#53-Jeff" → "53-Jeff"

So far I have this:

return preg_replace("/[^0-9a-zA-Z]/","", $val);

But being a regex novice, I can't figure out how to insert a space. I had odd results when I tried.

like image 738
jeffkee Avatar asked Nov 12 '11 21:11

jeffkee


1 Answers

Inserting a space is just as simple as you expect it to be:

preg_replace("/[^0-9a-zA-Z ]/", "", $val);

Btw. your third example is not clear to me: Do you want to replace the - too? If not, you need to add it to the character list too.

See this for a running example.

like image 142
poke Avatar answered Oct 22 '22 13:10

poke