用正则表达式替换文本中的相同URL

I am using the following code to add links to urls in text...

   if (preg_match_all("#((http(s?)://)|www\.)?([a-zA-Z0-9\-\.])(\w+[^\s\)\<]+)#i", $str, $matches))
   {
         ?><pre><?php
         print_r($matches);
         ?></pre><?php
         for ($i = 0; $i < count($matches[0]); $i++)
         {
             $url = $matches[0][$i];
             $parsed = parse_url($url);

             $prefix = '';
             if (!isset($parsed["scheme"])){
                $prefix = 'http://';
             }


             $url = $prefix.$url;

             $replace = '<a href="'.$url.'" class="auto_link_color">'.$matches[0][$i].'</a>';

             $str = str_replace($matches[0][$i], '<a href="'.$prefix.$matches[0][$i].'" class="auto_link_color">'.$matches[0][$i].'</a>', $str);
         }
     }

the problem comes when i enter twice the same url in the text at any place..

for example.

google.com text text google.com

it will add a link on the first one and then search for google.com which is inside the link and try to add again in there..

how can i make sure it will add the links separately without problems?

You can use preg_replace_callback() to reliably work on individual matches.