Removing spaces and anything that is not alphanumeric

与世无争的帅哥 提交于 2019-12-19 18:41:56

问题


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).


回答1:


Try this:

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



回答2:


$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.




回答3:


The solution that works for me is:

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

The + matches blocks of one or more occurances of \W whitespace which includes spaces and all non-alphanumeric characters




回答4:


Try

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


来源:https://stackoverflow.com/questions/4210419/removing-spaces-and-anything-that-is-not-alphanumeric

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!