Maximus
Maximus

Reputation: 2976

PHP regular expression skip element

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

Upvotes: 1

Views: 318

Answers (2)

rubber boots
rubber boots

Reputation: 15204

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

Upvotes: 0

Artefacto
Artefacto

Reputation: 97835

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.

Upvotes: 1

Related Questions