I need to write a script that will add an img-responsive class to HTML images.
So in the HTML code:
a) It will search if there are any <img>
tags with the class option, if so, it will add it to the current img-responsive class
b)If the image does not have a class, we only add a class with img-responsive.
Does anyone know how to do this?
My current code (it’s not working):
function addImgResponsiveClass($matches) {
if (!empty($matches[2])) {
$replacement = $matches[1] . 'class="' . $matches[2] . ' img-responsive"' . $matches[3];
} else {
$replacement = $matches[1] . 'class="img-responsive"' . $matches[2] . $matches[3];
}
return $replacement;
}
$txtD = preg_replace_callback(
'/(<imgs+)(class="([^"]*)"s*)?(.*?>)/i',
'addImgResponsiveClass',
dynamicCaption($dataArray[0]['content_pl'])
);
2
Answers
It seems to be an issue with your
regex
and theclass
attribute, hope the following helps:Do not use regex at all. That is not the right tool for manipulating and parsing HTML.
Note: LoadHTML() does only work if there is a root element. In this case there is none, so I create
html
as a wrapper and remove it on output. In case you have a full HTML file, you can omit that steps.