Saturday, October 29, 2011

PHP: Search URL in a string

When found an URL beginning with http://, add anchor tag to it.
 
Code:
<?php
$str = "bla http://www.example.com bla bla http://www.example.net bla bla";

$m = preg_match_all('/http:\/\/[a-z0-9A-Z.]+(?(?=[\/])(.*))/', $str, $match);

if ($m) {
 $links = $match[0];
 for ($j = 0; $j < $m; $j++) {
  $str = str_replace($links[$j],
  '<a href="'.$links[$j].'">'.$links[$j].'</a>',
  $str);
 }
}

echo "Content: ".$str; 
?>

Output:

Content: bla http://www.example.com bla bla http://www.example.net bla bla


Refer:
http://php.net/manual/en/function.preg-match-all.php
http://php.net/manual/en/function.preg-match.php

Other regex expressions to match URL format:
@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@
Refer: http://stackoverflow.com/questions/16113652/using-phps-preg-match-all-to-extract-a-url

1 comment:


  1. I like the way on how you put up your blogs. Wonderful and awesome. Hope to read more post from you in the future. Goodluck. Happy blogging!

    Bubble
    www.gofastek.com

    ReplyDelete