Home > PHP > Find links within text and convert to active links with PHP

Find links within text and convert to active links with PHP

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.

  1.  
  2.  
  3. function activateLinks($string)
  4. { 
  5.  
  6. // This regular expression looks for <strong>http:// </strong>type url
  7. $string = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',
  8. '<a href="1" target=_blank>1</a>', $string);
  9.  
  10. // This regular expression looks for <strong>www. </strong>type url
  11. $string = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',
  12. '1<a href="http://2" target=_blank>2</a>', $string);
  13.  
  14. // This regular expression looks for <strong>[email protected]</strong>
  15. $string = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
  16. '<a href="mailto:1" target=_blank>1</a>', $string);
  17.  
  18. return $string;
  19.  
  20. }
  21.  
  22. //call function where ever you need it
  23. $string= 'Scaling a dynamic background image in proportion using flashvisit
  24. (http://www.flashnutz.com) or email me on [email protected]';
  25.  
  26. echo activateLinks($string);
  27.  
  28.  

The output of the string would be

  1.  
  2. //output of $string
  3. $string = 'Scaling a dynamic background image in proportion using flash visit
  4. (<a href="http://www.flashnutz.com">http://www.flashnutz.com</a>) or
  5. email me on <a href="mailto:[email protected]"> [email protected]</a>';
  6.  

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

  1. July 29th, 2010 at 14:00 | #1

    mmm, thanks for the code but I am getting:

    Scaling a dynamic background image in proportion using flashvisit
    (1) or email me on 1

  2. July 29th, 2010 at 14:08 | #2

    mmmm, I am getting a deprecated message:

    http://www.php.net/manual/en/function.eregi-replace.php

    I suck in regex so I can not fix the issue.

  3. July 29th, 2010 at 15:29 | #3

    Hi Manuel,
    Try replacing eregi_replace(); with preg_replace();

  4. September 9th, 2010 at 03:51 | #4

    This regular expression looks for newarticle

    You can see above syntax is wrong, can anybody tell me how to change it to correct syntax
    means how to add inverted commas (“) to syntax using eregi_replace()?

  5. September 9th, 2010 at 03:53 | #5

    This regular expression looks for newarticle

    You can see above syntax is wrong, can anybody tell me how to change it to correct syntax
    means how to add inverted commas (“) to syntax using eregi_replace()?

  1. No trackbacks yet.
SEO Powered by Platinum SEO from Techblissonline