1

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?

anubhava
  • 761,203
  • 64
  • 569
  • 643
stergosz
  • 5,754
  • 13
  • 62
  • 133
  • 1
    You need to match the complete link. – Ed Heal Feb 25 '12 at 13:35
  • You could have a look at my answer to [Converting text to link](http://stackoverflow.com/questions/9410655/converting-text-to-link-php-regex-issue/9412798#9412798). – rodneyrehm Feb 25 '12 at 13:39
  • @rodneyrehm i tried your code but even if i type simple text it will try to add http:// at first – stergosz Feb 25 '12 at 13:49
  • well, yes, of course. A link without protocol (http://) will have a browser request it relative to the current domain. This is not what you want, so my replace function fixes that for you. – rodneyrehm Feb 25 '12 at 14:10
  • it seems to work now, another problem is that it doesnt work with text like google.com google.fr ... how can your regex be edited to work with urls that didnt have www or http at first? – stergosz Feb 25 '12 at 14:13

1 Answers1

1

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

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592