How to check if HTML content contains images with PHP

It is not difficult to check if the html content contains images.

However if you are using WordPress, WordPress core function would not present a good solution.

In my opinion, it is better using the PHP DOM to find out whether the contents have images or not.

function hasImg($string){
    $dom = new DOMDocument;
    $images = $dom->getElementsByTagName('img');
    foreach ($images as $image) {
        if($image->getAttribute('src') != '') return true;
    return false;

Some people may wonder, why we are not iterating through html contents to solve the problem. In most of case, PHP developers will suggest using DOM. It is more right answer than going through each characters to find where img HTML tags are.

No comments:

Post a Comment