Search code examples
phpregexhyperlinkhtml-parsingpreg-replace

Convert URLs to hyperlinks in HTML without replacing src attribute values


I'm trying to convert URLs, but not if they come after src=". So far, I have this...

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

It converts the URL, but even if it is before src=".


Solution

  • Make that a lookbehind assertion.

    (?<!^src=")