Posted By

Criptt on 03/31/12


regex url php link

Versions (?)

Who likes this?

1 person have marked this snippet as a favorite


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 ''

  1. <?php
  2. // this function shall search for any url that matches the pattern
  3. // like:
  4. //
  5. //
  6. //
  7. // those urls shall be replaced by a html link tag
  9. $text= preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '<a href="$1" target="blank">$1</a>', $text);
  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."
  14. $status = str_replace("href=\"www.","href=\"http://www.",$status);

Report this snippet  


RSS Icon Subscribe to comments
Posted By: Mccauleyray on December 18, 2018

I will try this definitely. 192,168,8,1 IP Login Guide.

You need to login to post a comment.