1

I have written regular expression which converts text links into clickable link. The code works fine however when an HTML tag is passed it mess the code

Here is my code

$text = preg_replace('#(?<![">])((http|ftp)s?://[^<>\s]+)#i', '<a href="\\0">\\0</a>', $text );

It is suppose to skip following element

<a href="http://www.yahoo.com">Yahoo</a>

but it does not.. what am I doing wrong?

Thanks

3
  • Can you show an element that should be replaced as well? Commented Aug 16, 2010 at 18:03
  • it converts url like yahoo.com to <a href="yahoo.com">http://yahoo.com</a> What I am trying to do is to skip the <a href tags Commented Aug 16, 2010 at 18:05
  • Use the PHP DOM functions to only apply the regex to text nodes that are not within A tags. Commented Aug 16, 2010 at 18:08

2 Answers 2

1

It does skip it. " is before the URL, so the negative look behind makes it not match.

Anyway, to do this reliably, you should be using a HTML parser. You could transform only text nodes not worrying about existing HTML elements.

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

Comments

0

After checking your code with two inputs:

$text1 = '<a href="http://www.yahoo.com">Yahoo</a>';
$text2 = 'text text http://www.yahoo.com text';

$reg = '{
         (?<![">])
         (
           (?:http|ftp)s? : // [^<>\s]+
         )
        }ix';

echo  preg_replace($reg, '<A HREF="\1">\1</A>', $text1 ) . "\n";
echo  preg_replace($reg, '<A HREF="\1">\1</A>', $text2 ) . "\n";

and reading the corresponding outputs:

=> #1 not touched  <a href="http://www.yahoo.com">Yahoo</a>
=> #2 modified     text text <A HREF="http://www.yahoo.com">http://www.yahoo.com</A> text

I'd ask you what you think what should be different?

Regards

rbo

2 Comments

#1 should output like <a href=" <a href="yahoo.com/"">http://www.yahoo.com/"</…>
There was space after <a href="<SPACE> so the rule was ignoring it. I added \s and its working now

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.