Posted By

Criptt on 03/31/12


Tagged

regex url php link


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

arkadylukashov


Replace url in a string with preg_replace even without http://


 / Published in: PHP
 

Many developers has trouble when they have to check for urls inside a large textual string. This solution will help you to change the url into html link tags even when the user only inserts a url like 'www.mysite.com'

  1. <?php
  2. // this function shall search for any url that matches the pattern
  3. // like:
  4. // www.mysite.com
  5. // http://www.mysite.com
  6. // http://mysite.com
  7. // those urls shall be replaced by a html link tag
  8.  
  9. $text= preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1" target="blank">$1</a>', $text);
  10.  
  11. //because you want the url to be an external link the href needs to start with 'http://'
  12. //simply replace any occurance of 'href="www.' into 'href="http://www."
  13.  
  14. $status = str_replace("href=\"www.","href=\"http://www.",$status);

Report this snippet  

You need to login to post a comment.