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
https://forums.phpfreaks.com/topic/126310-easy-preg-replace-change/
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..

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.