【问题标题】:Include backslash in regular expression for URL sanitize?在 URL 清理的正则表达式中包含反斜杠?
【发布时间】:2016-09-29 12:31:21
【问题描述】:

我有以下正则表达式:

$url = "http://example.com?param=test1\test2\test3\test4";

$cleanUrl = preg_replace('|[^a-z0-9-~+_.?\[\]\^#=!&;,/:%@$\|*`\'<>"()\\x80-\\xff\{\}]|i', '', $url);

我得到以下输出:

http://example.com?param=test1est2est3est4

但是, 我期待以下输出:

http://example.com?param=test1\test2\test3\test4

我尝试了这个正则表达式,但它不起作用:

    $cleanUrl = preg_replace('|[^a-z0-9-~+_.?\[\]\^\\#=!&;,/:%@$\|*`\'<>"()\\x80-\\xff\{\}]|i', '', $url);
                                                    ^ escaped single quote

【问题讨论】:

  • 您确定输入字符串吗?见ideone.com/OnepGA。我认为应该是$url = "http://example.com?param=test1\\test2\\test3\\test4";。然后使用$cleanUrl = preg_replace('|[^-\\\\a-z0-9~+_.?\[\]\^#=!&amp;;,/:%@$\|*`\'&lt;&gt;"()\x80-\xff\{\}]|i', '', $url);。见this demo
  • 您必须使用 \\\\ 来转义反斜杠。阅读此SO Answer

标签: php regex url


【解决方案1】:

也许,您正在做的事情可以通过其他方式实现,但回答您的问题,我应该注意您的输入字符串不包含反斜杠,它包含 tab 字符作为双引号字符串文字, \t 定义转义序列。

使用单引号文字后,\t 表示 2 个符号。现在,正则表达式没有\。你需要用\\\\添加它:

$url = 'http://example.com?param=test1\test2\test3\test4';
$cleanUrl = preg_replace('|[^-\\\\a-z0-9~+_.?\[\]^#=!&;,/:%@$\|*`\'<>"()\x80-\xff{}]|i', '', $url);
echo $cleanUrl;

this PHP demo打印http://example.com?param=test1\test2\test3\test4

我还将- 移到了开头(如果它应该匹配文字连字符,最好将它放在字符类的开头或结尾),并且^ 不在开头不必转义 char 类中的位置。 {}[ 也是如此,但方括号更好地转义(某些正则表达式风格不允许在字符类中未转义的 [)。

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 2012-06-01
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    相关资源
    最近更新 更多