1

Possible Duplicate:
php regex to match outside of html tags

I found a nice function here: https://stackoverflow.com/a/1945957

It converts text URLs to proper links, but it also matches URLs in tags such as <img>. Can the function be modified to only match URLs that are not in quotes (single or double)?

Thanks

/**
 * Replace links in text with html links
 *
 * @param  string $text
 * @return string
 */
function auto_link_text($text)
{
   $pattern  = '#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#';
   $callback = create_function('$matches', '
       $url       = array_shift($matches);
       $url_parts = parse_url($url);

       $text = parse_url($url, PHP_URL_HOST) . parse_url($url, PHP_URL_PATH);
       $text = preg_replace("/^www./", "", $text);

       $last = -(strlen(strrchr($text, "/"))) + 1;
       if ($last < 0) {
           $text = substr($text, 0, $last) . "&hellip;";
       }

       return sprintf(\'<a rel="nofollow" href="%s">%s</a>\', $url, $text);
   ');

   return preg_replace_callback($pattern, $callback, $text);
}

Input:

<img src = "http://www.google.com/logo.png" /> http://www.google.com

Expected output:

<img src = "http://www.google.com/logo.png" /> <a rel="nofollow" href="http://www.google.com">http://www.google.com</a>

Solved:

#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))(?=[^>]*(<|$))#
Community
  • 1
  • 1
lol768
  • 21
  • 2
  • I did actually search before asking the question, but I couldn't get it to work properly. – lol768 Nov 17 '12 at 17:24
  • Yes, I believe that. But those links are difficult to find unless you know what to look for. It's a complex topic, check all three as they cover variations. (Also: duplicates aren't bad per se. This is for hypertextiness here.) – mario Nov 17 '12 at 17:27
  • @OlafDietsche I can't yet. "Users with less than 10 reputation can't answer their own question for 8 hours after asking. You may self-answer in 4 hours. Until then please use comments, or edit your question instead." – lol768 Nov 17 '12 at 20:41

0 Answers0