Removing spaces and anything that is not alphanumeric

I am trying to remove anything that is not alphanumeric, or a space with _:

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

What I am doing wrong here does not seem to work. I tried several combinations of regular expressions ... (and I'm generally not very bright).

+6
php regex alphanumeric
source share
4 answers

Try the following:

 $filename = preg_replace("/[^a-zA-Z0-9 ]/", "_", $filename); 
+11
source share
 $filename = preg_replace('~[\W\s]~', '_', $filename); 

If I understand your question correctly, you want to replace any space (\ s) or non-alphanumeric (\ W) character with "_". It must succeed. Note that \ W is uppercase, as opposed to lowercase \ w, which matches alphanumeric characters.

+7
source share

The solution that works for me is:

 $filename = preg_replace('/\W+/', '_', $filename); 

+ matches blocks of one or more \W space events, which includes spaces and all non-alphanumeric characters

+2
source share

Try

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

All Articles