regex help please replace URLs to links

Discussion in 'PHP' started by JEET, Mar 9, 2012.

  1. #1
    Hello,
    I'm using the following pattern to replace URLs into links:

    /http:\/\/([a-zA-Z0-9\?\&\%\.\;\:\/\=\+\_\-]*)/is

    It works, but it also replaces the links that are already there in the html, thus breaking them...
    
    <a href="http://someurl.com"> some url </a> http://anotherone.com
    
    Code (markup):
    Both the http:)//) get replaced, and first one breaks...

    How do I change it so it neglects the ones with (") sign in suffix and prefix?
    "http://someurl.com" does not get replaced.

    I don't want to use \s because sometimes the URL might be followed by a < or sign or a \r\n etc...
    Thanks
     
    JEET, Mar 9, 2012 IP
  2. prabhunimish

    prabhunimish Member

    Messages:
    15
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    46
    #2
    see if this works :

    $modified_str = preg_replace('/(?<!http:\/\/)(www.[-a-zA-Z0-9@:%_\+.~#?&\/=]+)/i', '<a href="http://\1">\1</a>', $str)
    Code (markup):
     
    prabhunimish, Mar 9, 2012 IP