问题
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