Jump to content

preg_replace random url link?


joe92

Recommended Posts

Ha, it was something simple :D

 

$replaceUrlPrt5 = preg_replace("/^(?<!href=\")((https?:\/\/)(www\.|ftp\.)?[\w\-]+\.[^\s]+?)(?!\")$/ism", "<a class=\"nWhite\" href=\"\\1\" target=\"_blank\">\\1</a>", $replaceUrlPrt4);

 

It was a case of placing anchors around the pattern, and also linking to the right parenthesis, as the look behind doesn't count! :facepalm:

 

However, I found a new question... The positioning of the anchors around pattern, will the following patterns return different results? I have tried them both and they seem to return the same result. However, is one way better than the other, or is it just a case of tit for tat?

 

1. /^(?<!href=\")((https?:\/\/)(www\.|ftp\.)?[\w\-]+\.[^\s]+?)(?!\")$/ism
2. /(?<!href=\")^((https?:\/\/)(www\.|ftp\.)?[\w\-]+\.[^\s]+?)$(?!\")/ism

Wait, it didn't work properly. I tested using only one link, forgetting to try it in random orders. I'm tired, that's my excuse. ::)

 

It worked if the link was at the end of the page. The obvious solution is to remove the $ anchor at the end of the pattern. However, if the link is at the end of a paragraph this then turns everything up to the end of the <br/> into a link as it is set to read as multi-line. So it required making sure there wasn't a '<' in the character class at the end. The following pattern works... (so far, fingers crossed no errors appear)

 

$replaceUrlPrt5 = preg_replace("/^(?<!href=\")((https?:\/\/)(www\.|ftp\.)?[\w\-]+\.[^\s\<]+)(?!\")/ism", "<a class=\"nWhite\" href=\"\\1\" target=\"_blank\">\\1</a>", $replaceUrlPrt4);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.