Skip to content Skip to sidebar Skip to footer

Convert Text Link To Html With Context Considered

I want to convert links such as http://google.com/ to HTML, however if they're already in an HTML link, either in the href='' or in the text for the link, I don't want to convert t

Solution 1:

Do not use regular expressions for (X)HTML parsing. Use DOM instead! The XPath//text()[not(ancestor::a) and contains(., 'http://')][1] should find the first text node containing at least one HTTP URL that is not itself contained in an anchor tag. You may naively replace the text node with a text node containing preceding text, an anchor element node containing href attribute and href text node, and a text node containing remaining text. Do that until you find no more text nodes matching the XPath.

Solution 2:

Based on mario's comment to my original post:

preg_replace('@(?<!href="|src="|">)(https?:\/\/([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1">$1</a>', $text);

Works perfectly for replacing bbpress's unknown pasta salad.

Post a Comment for "Convert Text Link To Html With Context Considered"