regex - Using preg_replace inside tag -
i change url img src tag value 1 string second this:
$str1 = "< img src="//d3kq20n0vvk93.cloudfiojiojront.net/cbbcadjiojoijc470efd702jijiojoijiojioc4.jpg" alt="">";
to:
$str2 = "< img src="//d3kq20n0vvk93.cloudfiojiojront.net/cbbcadjiojoijc470efd702jijiojoijiojioc4.jpg?ttl=3600/" alt="">";
i tried way doesn't work inside src="" tag:
print preg_replace('/<img\s.*?\bsrc="(.*?)".*?>/si', "$0?ttl=3600", $str);
how can resolve it? in advance
it doesn't work because $0
refers whole match (from <img
until >
) , obtain <img...>?tll=3600
.
what need change src content, can:
use capturing groups:
echo preg_replace('~(<img\s.*?\bsrc=".*?)(".*?>)~si', '$1?ttl=3600$2', $str);
use
\k
(that resets begining of match match result) , lookahead (that performs check , not part of match result)echo preg_replace('~<img\s.*?\bsrc=".*?\k(?=".*?>)~si', '?ttl=3600', $str);
however, keep in mind html code can full of traps (attribute between single quotes or no quotes @ all, img tags no src attribute, undefined number of spaces around equal sign, attribute value or text content contains string src="
...). reason why, cleanest solution use specific tool deal html.
an example domdocument:
$dom = new domdocument(); @$dom->loadhtml($str); $imgnodes = $dom->getelementsbytagname('img'); foreach($imgnodes $imgnode) { if ($imgnode->hasattribute('src') && !empty($src = $imgnode->getattribute('src'))) $imgnode->setattribute('src', $src . '?ttl=3600'); } $result = $dom->savehtml();
if treat piece of html , not whole document, , if php version greater or equal 5.3.6, can replace last line with:
$result = $dom->savehtml($dom->getelementsbytagname('body')->item(0)); $result = substr($result, 6, -7);
Comments
Post a Comment