I’m looking for a way to find/replace links to images (within user-generated content) without touching links to non-images.
For example, the following text:
<a href="http://domain.com/arbitrary-file.jpg">Text</a>
<a href="http://domain.com/arbitrary-file.jpeg">Text</a>
<a href="http://domain.com/arbitrary-path/arbitrary-file.gif">Text</a>
<a href="http://domain.com/arbitrary-file.png">Text</a>
<a href="http://domain.com/arbitrary-file.html">Text</a>
<a href="http://domain.com/arbitrary-path/">Text</a>
<a href="http://domain.com/arbitrary-file#anchor_to_here">Text</a>
Non-hyperlinked URL: http://domain.com/arbitrary-path/arbitrary-file.gif
Non-hyperlinked URL: http://domain.com/arbitrary-file#anchor_to_here
… should be revised to:
<img src="http://domain.com/image.jpg" alt="Text" />
<img src="http://domain.com/arbitrary-file.jpeg" alt="Text" />
<img src="http://domain.com/arbitrary-path/arbitrary-file.gif" alt="Text" />
<img src="http://domain.com/arbitrary-file.png" alt="Text" />
<a href="http://domain.com/arbitrary-file.html">Text</a>
<a href="http://domain.com/arbitrary-path/">Text</a>
<a href="http://domain.com/arbitrary-file.html#anchor_to_here">Text</a>
Non-hyperlinked URL: http://domain.com/arbitrary-path/arbitrary-file.gif
Non-hyperlinked URL: http://domain.com/arbitrary-file#anchor_to_here
… securely and reliably in PHP.
There’s no reliable way to do this, not at least with regular expressions, but this should do the trick nevertheless:
To open this up a bit:
<atags"character</a>tag in the replaceAs Bauer noted, you could be better off using DOM methods. But if you can be sure your links are always in this format, you can use regular expressions. Regex might be a bit faster also.