skip to Main Content

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


  1. It seems to be an issue with your regex and the class attribute, hope the following helps:

    function addImgResponsiveClass($matches) {
        if (!empty($matches[2])) {
            $replacement = $matches[1] . 'class="' . trim($matches[2]) . ' img-responsive"' . $matches[4];
        } else {
            $replacement = $matches[1] . 'class="img-responsive" ' . $matches[4];
        }
        return $replacement;
    }
    
    $txtD = preg_replace_callback(
        '/(<imgs+)(class="([^"]*)"s*)?(.*?>)/i',
        'addImgResponsiveClass',
        dynamicCaption($dataArray[0]['content_pl'])
    );
    
    Login or Signup to reply.
  2. 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.

    $html = <<<'_HTML_'
    <img alt="no class">
    <img class="" alt="empty class">
    <img class="lazyload" alt="lazyload">
    _HTML_;
    
    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $dom->loadHTML('<html>' . $html . '</html>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    
    foreach ($dom->getElementsByTagName('img') as $image) {
        $class = $image->getAttribute('class') ?? '';
        $image->setAttribute('class', ltrim($class . ' img-responsive'));
    }
    
    echo str_replace(['<html>', '</html>'], '', $dom->saveHTML());
    
    <img alt="no class" class="img-responsive">
    <img class="img-responsive" alt="empty class">
    <img class="lazyload img-responsive" alt="lazyload">
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search