简体   繁体   中英

php regex to add class to images without class

I'm looking for a php regex to check if a image don't have any class, then add "img-responsive" to that image's class.

thank you.

Instead of looking to implement a regular expression, make effective use of DOM instead.

$doc = new DOMDocument;
$doc->loadHTML($html); // load the HTML data

$imgs = $doc->getElementsByTagName('img');

foreach ($imgs as $img) {
  if (!$img->hasAttribute('class'))
      $img->setAttribute('class', 'img-responsive');
}

I would be tempted to do this in JQuery. That offers all the functionality you need in a few lines.

$(document).ready(function(){
    $('img').not('img[class]').each(function(e){
        $(this).addClass('img-responsive');
    });
});

If you have the output in PHP then a HTML parser is the way to do it. Regular expressions will always fail, in the end. If you don't want to use a parser, but you have the HTML code you can try to do it with plain and simple PHP code:

function addClassToImagesWithout($html)
// this function does what you want, given well-formed html
{
  // cut into parts where the images are
  $parts = explode('<img',$html);
  foreach ($parts as $key => $part)
  {
    // spilt at the end of tags, the image args are in the first bit
    $bits = explode('>',$part); 
    // does it not contain a class
    if (strpos($bits[0],'class=') !== FALSE)
    {
      // insert the class
      $bits[0] .= " class='img-responsive'";
    } 
    // recombine the bits
    $part[$key] = implode('>',$bits);  
  }
  // recombine the parts and return the html
  return implode('<img',$parts);  
}

this code is untested and far from perfect, but it shows that regular expressions are not needed. You will have to add in some code to catch exceptions.

I must stress that this code, just like regular expressions will ultimately fail when, for instance, you have something like id='classroom' , title='we are a class apart' or similar. To do a better job you should use a parser:

http://htmlparsing.com/php.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM