<?php

function linkify($input){
    $re = <<<'REGEX'
!
    (
      <\w++
      (?:
        \s++
      | [^"'<>]++
      | "[^"]*+"
      | '[^']*+'
      )*+
      >
    )
    |
    (\b https?://[^\s"'<>]++ )
    |
    (\b www\d*+\.\w++[^\s"'<>]++ )
!xi
REGEX;
    
    return preg_replace_callback($re, function($m){
        if($m[1]) return $m[1];
        $url = htmlspecialchars($m[2] ? $m[2] : "http://$m[3]");
        $text = htmlspecialchars("$m[2]$m[3]");
        return "<a rel='nofollow' href='$url'>$text</a>";
    },
    $input);
}

echo linkify("<img src='http://foo'>www.test.com/?x&y");

?>