Replace non-html links with <A> tags
Posted
by tombazza
on Stack Overflow
See other posts from Stack Overflow
or by tombazza
Published on 2010-01-26T11:53:09Z
Indexed on
2010/06/03
17:14 UTC
Read the original article
Hit count: 145
I have a block of code that will take a block of text like the following:
Sample text sample text http://www.google.com sample text
Using the preg_replace_callback
method and the following regular expression:
preg_replace_callback('/http:\/\/([,\%\w.\-_\/\?\=\+\&\~\#\$]+)/',
create_function(
'$matches',
'$url = $matches[1];
$anchorText = ( strlen($url) > 35 ? substr($url, 0, 35).\'...\' : $url);
return \'<a href="http://\'. $url .\'">\'. $anchorText .\'</a>\';'),
$str);
Will convert the sample text to look like:
Sample text sample text < a href="http://www.google.com">http://www.google.com< /a> sample text
My problem now is that we have introduced a rich text editor that can create links before being sent to the script. I need to update this piece of code so that it will ignore any URLs that are already inside an tag.
© Stack Overflow or respective owner