Jump to content

Easy Preg Replace Change


johnsmith153

Recommended Posts

Very quick (if you know how)

 

I have this script which transfers a web address into the <a href

 


preg_replace('!(http://)?(www\.[a-z._-]+?\.[a-z]{1,4}\.?[a-z]{1,4}(/[a-z0-9._+,-/]+)?)!i', '<a href="http://$2" target="_blank" >$0</a>', $url);

 

However I have noticed that www.24.com (or any address with a number in it is not picked up.) What changes do I need to make to the code above to get it to pick up numbers?

Link to comment
Share on other sites

To: www\.[a-z\d._-]+?

 

This segment of the pattern alone poses an issue. Notice the first dot which is escaped after the www (which is ok).. but notice that second dot in the character class? Since it is in a class, it is no longer considered a meta character.. result? It is now acceptable to have two dots back to back (in accordance to the pattern).

 

Consider the following:

 

$str = 'www..hello'; // yes, I know this is not a valid email.. it's to illustrate the dual dots
echo $str . '<br />'; // ouputs: www..hello 
$str = preg_replace('#www\.[a-z\d._-]+?#', '', $str);
echo $str; // ouputs: hello

 

You need to remove the dot from the character class, as no URL starts with www..

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.