[Edited - Sorry Bart] I\'ve looked at other answers but struggling to match this. I want to wrap an image tag where the src is the second attribute (after title) with a specific
Try this :
$newString = preg_replace('`<img([^>]*)src="\\.\\./\\.\\./images/([^"]+)"([^>])*>`','<a href="event:images/expand/$2"><img$1src="images/$2"$3></a>', $oldString);
Limitations are :
<input value='<img src="../../images/test.jpg/>"'/>
"
are replaced by '
in your img tags, you'll have to change the regexp<img alt="6>5" src="../../images/test.png"/>
I agree with other commenters saying regexp are bad to parse HTML. But there's almost no parsing here and the format of things to replace seems to be under control (generated by tinymce).
Similar questions have been answered several times and the answer is always the same: do not use regular expressions to tamper with HTML. In PHP, you can use XPath and the SimpleXml or DOMParser extensions to solve this problem.
Sorry for posting so many links to my own answers but the answers themselves and the questions they are answering contain a lot of information on the subject.
Try this code:
<?php
$str = '<img title="who_main_Layer_1.jpg" src="../../images/who_main_Layer_1.jpg" alt="who_main_Layer_1.jpg" width="380" height="268" />';
preg_match('#src="(?:.*/)?(.*?)"#', $str, $match);
$src = $match[1];
?>
<a href="event:images/expand/<?php echo $src; ?>"><img src=”images/<?php echo $src; ?>” /></a>
EDIT: another version to account for multiple tags in the string:
$replace = '<a href="event:images/expand/$1"><img src="images/$1" /></a>';
$str = preg_replace('#<\s*img.*?src="(?:[^"]+/)?(.*?)".*?>#s', $replace, $str);