php preg_replace 除了数字、字母、句点和斜线之外的所有内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8207069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
preg_replace all but numbers, letters, periods, and slash?
提问by user547794
I have a regular expression that strips everything but letters. numbers, and periods. How do I also add foreslashes to it?
我有一个正则表达式,可以去除除字母以外的所有内容。数字和句号。我如何还添加前斜杠?
$targetFile = preg_replace('/[^A-Za-z0-9-.]/', '', $targetFileDirty);
回答by mikel
You can escape the foreslash by putting a backslash before it - $targetFile = preg_replace('/[^A-Za-z0-9-.\/]/', '', $targetFileDirty);
您可以通过在前斜杠之前放置反斜杠来逃避前斜杠 - $targetFile = preg_replace('/[^A-Za-z0-9-.\/]/', '', $targetFileDirty);
Alternatively, and perhaps better, you can use different delimiters instead, e.g. $targetFile = preg_replace('#[^A-Za-z0-9-./]#', '', $targetFileDirty);
或者,也许更好,您可以使用不同的分隔符,例如 $targetFile = preg_replace('#[^A-Za-z0-9-./]#', '', $targetFileDirty);
回答by Toto
To be unicode compatible you can use:
要与 unicode 兼容,您可以使用:
$targetFile = preg_replace('#[^\pL\pN./-]+#', '', $targetFileDirty);
回答by Christopher
Simply add an escaped slash: [^A-Za-z0-9-.\\/]
只需添加一个转义斜线: [^A-Za-z0-9-.\\/]