且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何防止被第二个正则表达式重新替换?

更新时间:2023-02-06 19:50:19

$str = preg_replace_callback('/[([^][]*)](([^()]*))|((?:(?: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])),如果是,则您的第二个正则表达式与字符串匹配并替换普通链接, 否则替换为链接/链接文本.

One way would be to do it like this. You merge your two expressions together with the alternative character |. Then in your callback function you just check if your third capture group is set (isset($matches[3])) and if yes, then your second regular expression matched the string and you replace a normal link, otherwise you replace with link/linktext.

我希望你明白一切,我可以帮助你.

I hope you understand everything and I could help you.