PHPBuilder - Easy function to link URLs

RSS Twitter
Snippets Html

Easy function to link URLs

by: Jeroen Hennion
October 29, 2001

Version: 1.0

Type: Function

Category: HTML

License: GNU General Public License

Description: I searched the net for a long time to find a bugless and short PHPfunction to easily link URLs. But most of the functions were either too long or they had two bugs: 1. When one puts the URL between single quotes ('), there is an error if the string is put in a MySQL-database by the script after the function is executed (because strings are between single quotes there) 2. When one put a full stop or question mark after the URL, the full stop or question mark is linked too. So I made my own function:

function link_urls($string) {
  //change single to double quotes (only necessary if you work with databases)
  $string = ereg_replace("\'", "\"", $string);
  //change full stops and question marks that don't need to be linked
  $string = ereg_replace("\? ", " question_mark ", $string);
  $string = ereg_replace("\?\r\n"," question_mark_new_line ", $string);
  $string = ereg_replace("\. ", " full_stop ", $string);
  $string = ereg_replace("\.\r\n"," full_stop_new_line ", $string);
  $string = eregi_replace("((ftp://)|(http://)|(www))(([a-z0-9.\-])*)(@)?(([a-z0-9\.])*)(([:/])?)((([a-z0-9]*)(@?)/*)+([.a-z]{2,4}){1})?((\??[a-z0-9\=]*)?)((\&[a-z0-9\=]*)?)(([\.a-z]){2,4})?", "<a href=\"\\0\">\\0</a>", $string);
  //change back dots and question marks
  $string = ereg_replace(" full_stop_new_line ", "\.\r\n", $string);
  $string = ereg_replace(" full_stop", "\.", $string);
  $string = ereg_replace(" question_mark_new_line ", "\?\r\n", $string);
  $string = ereg_replace(" question_mark", "\?", $string);
  return $string;

Comment and Contribute

Your comment has been submitted and is pending approval.

Jeroen Hennion



(Maximum characters: 1200). You have characters left.