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?

5
  • 1
    You need to match the complete link. Commented Feb 25, 2012 at 13:35
  • You could have a look at my answer to Converting text to link. Commented Feb 25, 2012 at 13:39
  • @rodneyrehm i tried your code but even if i type simple text it will try to add http:// at first Commented Feb 25, 2012 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. Commented Feb 25, 2012 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? Commented Feb 25, 2012 at 14:13

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.