Using regexp to replace url with hyperlink.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Markus
    Recognized Expert Expert
    • Jun 2007
    • 6092

    #1

    Using regexp to replace url with hyperlink.

    Now, i've put my hand to this and it just burns me..

    How would i go about taking some user input
    [php]
    $_userInput = "http://www.somesite.co m is a great site!";
    [/php]
    and changing it so that it was wrapped in a hyperlink
    [php]
    $_userInput = "<a href=\"http://www.somesite.co m\">http://www.somesite.co m</a> is a great site!";
    [/php]

    Any ideas?
    Much appreciated.
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    Try this one for you.
    [php]$pattern_url = '~(?>[a-z+]{2,}://|www\.)(?:[a-z0-9]+(?:\.[a-z0-9]+)?@)?(?:(?:[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])(?:\.[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])+|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?:/[^\\/:?*"<>|\n]*[a-z0-9])*/?(?:\?[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?(?:&[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?)*)?(?:#[a-z0-9_%.]+)?~i';

    $text="http://www.somesite.co m is a great site!";
    echo preg_replace($p attern_url,"<a href=\"\\0\">\\ 0</a>", $text);[/php]
    Ronald

    Comment

    • Markus
      Recognized Expert Expert
      • Jun 2007
      • 6092

      #3
      Originally posted by ronverdonk
      Try this one for you.
      [php]$pattern_url = '~(?>[a-z+]{2,}://|www\.)(?:[a-z0-9]+(?:\.[a-z0-9]+)?@)?(?:(?:[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])(?:\.[a-z](?:[a-z0-9]|(?<!-)-)*[a-z0-9])+|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?:/[^\\/:?*"<>|\n]*[a-z0-9])*/?(?:\?[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?(?:&[a-z0-9_.%]+(?:=[a-z0-9_.%:/+-]*)?)*)?(?:#[a-z0-9_%.]+)?~i';

      $text="http://www.somesite.co m is a great site!";
      echo preg_replace($p attern_url,"<a href=\"\\0\">\\ 0</a>", $text);[/php]
      Ronald
      Works a charm, ronver!

      Could you grace me with the logic behind it all, please?

      Comment

      • ronverdonk
        Recognized Expert Specialist
        • Jul 2006
        • 4259

        #4
        When I can find the time I will. Made this one, after nights of sweat, many years ago and I still use it.

        Ronald

        Comment

        Working...