在输入的过程中,我有两个regex,它们是:
// replace a URL with a link which is like this pattern: [LinkName](LinkAddress)
$str= preg_replace("/\[([^][]*)]\(([^()]*)\)/", "<a href='$2' target='_blank'>$1</a>", $str);
// replace a regular URL with a link
$str = preg_replace("/(\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|])/i","<a href=\"$1\" target=\"_blank\">untitled</a>", $str);现在出现了一个问题(某种程度上是碰撞)。对于常规URL,一切都很好。但是对于基于模式的URL,存在一个问题:第一个regex创建该链接,第二个regex 再次创建一个href-attribute值的链接。
我怎么才能修好它?
编辑:根据评论,如何创建单个regex而不是这两个regex?(使用preg_replace_callback__)。老实说,我试过了,但对任何一种网址都没用..
有可能把它们结合起来吗?因为这些输出是不一样的。第一个有一个LinkName,第二个有一个常量字符串untitled作为它的LinkName。
发布于 2015-12-22 02:19:32
$str = preg_replace_callback('/\[([^][]*)]\(([^()]*)\)|(\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|])/i',
function($matches) {
if(isset($matches[3])) {
// replace a regular URL with a link
return "<a href='".$matches[3]."' target='_blank'>untitled</a>";
} else {
// replace a URL with a link which is like this pattern: [LinkName](LinkAddress)
return "<a href=".$matches[2]." target='_blank'>".$matches[1]."</a>";
}
}, $str);
echo $str;一种方法就是这样做。将两个表达式与替代字符|合并在一起。然后,在回调函数中,只需检查第三个捕获组是否设置(isset($matches[3])),如果是,则第二个正则表达式与字符串匹配,替换一个普通链接,否则将替换为链接/链接文本。
我希望你能理解一切,我能帮你。
https://stackoverflow.com/questions/34406286
复制相似问题