且构网

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

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

更新时间:2023-02-06 20:25:43

$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;

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.

相关阅读

技术问答最新文章