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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.