php – 使用preg_replace的’&’char的Regexp
发布时间:2020-12-13 15:57:53 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试解析包含的URL与preg_replace. $content = preg_replace('#https?://[a-z0-9._/?=-]+#i','a href="$0" target="_blank"$0/a',$content); 但是我将它用于用户评论,所以我也使用htmlspecialchars()函数来阻止XSS. function formatContributionConte
我正在尝试解析包含&的URL与preg_replace.
$content = preg_replace('#https?://[a-z0-9._/?=&-]+#i','<a href="$0" target="_blank">$0</a>',$content); 但是我将它用于用户评论,所以我也使用htmlspecialchars()函数来阻止XSS. function formatContributionContent($content) { $content = nl2br(htmlspecialchars($content)); // Regexp for mails $content = preg_replace('#[a-z0-9._-]+@[a-z0-9._&-]{2,}.[a-z]{2,4}#','<a href="mailto:$0">$0</a>',$content); // Regexp for urls $content = preg_replace('#https?://[a-z0-9._/?=&-]+#i',$content); var_dump($content); } formatContributionContent('https://openclassrooms.com/index.php?page=3&skin=blue'); 并且htmlspecialchars转换&进入“& amp;”所以我的正则表达式会产生错误的结果.确实,使用以下URL. http://www.siteduzero.com/index.php?page=3&skin=blue 我得到了; <a href="https://openclassrooms.com/index.php?page=3&" target="_blank">https://openclassrooms.com/index.php?page=3&</a>;skin=blue 解决方法
你可以加 ”;”在你的正则表达式匹配的字符列表中,如下所示:
$content = preg_replace('#https?://[a-z0-9._/?=&;-]+#i',$content); 这样,“&”字符在“& amp;”中转换通过htmlspecialchars,但你的正则表达式可以找到整个网址. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |