Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing spaces and anything that is not alphanumeric

I'm trying to remove everything that is not alphanumeric, or is a space with _:

$filename = preg_replace("([^a-zA-Z0-9]|^\s)", "_", $filename);

What am I doing wrong here, it doesn't seem to work. I've tried several regex combinations...(and I'm generally not very bright).

like image 692
jonnnnnnnnnie Avatar asked Nov 17 '10 23:11

jonnnnnnnnnie


2 Answers

Try this:

$filename = preg_replace("/[^a-zA-Z0-9 ]/", "_", $filename);
like image 57
cdhowie Avatar answered Oct 20 '22 18:10

cdhowie


$filename = preg_replace('~[\W\s]~', '_', $filename);

If I understand your question correctly, you want to replace any space (\s) or non-alphanumerical (\W) character with a '_'. This should do fine. Note the \W is uppercase, as opposed to lowercase \w which would match alphanumerical characters.

like image 43
lheurt Avatar answered Oct 20 '22 17:10

lheurt