php - preg_replace to replace string for matching url -
function makelinksinthecontent($html) { $html= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" rel=\"nofollow\" >$3</a>", $html); $html= preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" rel=\"nofollow\" >$3</a>", $html); $html= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:$2@$3\" rel=\"nofollow\">$2@$3</a>", $html); return($html); }
this code.
my need autolinking url. using preg_replace find url , set link url.
for example: "a page contains www.google.com." if pass content makelinksinthecontent($html), return "a page contains www.google.com."
but following url format not getting linked.
www.test.com()and[]&^%$#@!+|!@#$%^&()_+}{:"?><,./;'[]=-09~`.co,in,com.com
http://www.test.com()and[]&^%$#@!+|!@#$%^&()_+}{:"?><,./;'[]=-09~`.co,in,com.com
https://www.test.com()and[]&^%$#@!+|!@#$%^&()_+}{:"?><,./;'[]=-09~`.co,in,com.com
ftp://www.test.com()and[]&^%$#@!+|!@#$%^&()_+}{:"?><,./;'[]=-09~`.co,in,com.com
i think regular expression have mistakes. please suggest us.
you can use preg_replace_callback
in case. read more
function
<?php function replace_urls( $text = null ) { $regex = '/((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/'; return preg_replace_callback( $regex, function( $m ) { $link = $name = $m[0]; if ( empty( $m[1] ) ) { $link = "http://".$link; } return '<a href="'.$link.'" target="_blank" rel="nofollow">'.$name.'</a>'; }, $text ); } ?>
usage
<?php $text = "http://stackoverflow.com/questions/17854971/preg-replace-to-replace-string-for-matching-url#17855054 www.google.com https://twitter.com/ http://www.somelinkwithhash.com/post/4454/?foo=bar#foo=bar"; echo replace_urls( $text ); ?>
output
<a href="http://stackoverflow.com/questions/17854971/preg-replace-to-replace-string-for-matching-url#17855054" target="_blank" rel="nofollow">http://stackoverflow.com/questions/17854971/preg-replace-to-replace-string-for-matching-url#17855054</a> <a href="http://www.google.com" target="_blank" rel="nofollow">www.google.com</a> <a href="https://twitter.com/" target="_blank" rel="nofollow">https://twitter.com/</a> <a href="http://www.somelinkwithhash.com/post/4454/?foo=bar#foo=bar" target="_blank" rel="nofollow">http://www.somelinkwithhash.com/post/4454/?foo=bar#foo=bar</a>
Comments
Post a Comment