Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

php - How to prevent of re-replacing by second regex?

I have two regex(s) on the way of my input, these:

// 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("/((?:(?:https?|ftp)://|www.)[-a-z0-9+&@#/%?=~_|!:,.;]*[-a-z0-9+&@#/%=~_|])/i","<a href="$1" target="_blank">untitled</a>", $str);

Now there is a problem (somehow a collision). For regular URLs everything is fine. But for a pattern-based URLs, there is a problem: The first regex create a link of that and second regex again create a link of its href-attribute value.

How can I fix it?

Edit: According to the comments, how can I create a single regex instead of those two regex? (using preg_replace_callback). Honestly I tried it but it doesn't work for none kind of URLs ..

Is combining them possible? Because the output of those isn't identical. The first one has a LinkName and the second one has a constant string untitled as its LinkName.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
$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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...