Find links within text and convert to active links with PHP
July 12th, 2010
5 comments
Recently I have had to integrate some tweets into a clients website via RSS. The problem I found is that the links are hidden in the description and are not active. The solution is as simple as using 3 regular expressions and replace the text URL with a HTML URL using PHPs eregi_replace function.
function activateLinks($string) { // This regular expression looks for <strong>http:// </strong>type url $string = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)', '<a href="1" target=_blank>1</a>', $string); // This regular expression looks for <strong>www. </strong>type url $string = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)', '1<a href="http://2" target=_blank>2</a>', $string); // This regular expression looks for <strong>[email protected]</strong> $string = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})', '<a href="mailto:1" target=_blank>1</a>', $string); return $string; } //call function where ever you need it $string= 'Scaling a dynamic background image in proportion using flashvisit (http://www.flashnutz.com) or email me on [email protected]'; echo activateLinks($string);
The output of the string would be
//output of $string $string = 'Scaling a dynamic background image in proportion using flash visit (<a href="http://www.flashnutz.com">http://www.flashnutz.com</a>) or email me on <a href="mailto:[email protected]"> [email protected]</a>';
My next post will be how to read your twitter posts with php and then use this function to active the links within them.
Happy coding...
