Home » Php » php – Count length of images in a string

php – Count length of images in a string

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am trying to get length of images in a string.

My string

$page="<img><img><img><img>";

From the string above ,I want to get the output “4 images”.

I tried preg_match_all() and count() function, but it always returns “1 images”.

$page="<img><img><img><img>";
preg_match_all("/<img>/",$page,$m);
echo count($m);

Is there any other way to know how much images are in a string?

How to&Answers:

Preg_match_all returns a multidimensional array. The arrays are the capture groups. Since you aren’t capturing anything you want to count the 0 index of $m (which is all found values). So use:

echo count($m[0]);

For demonstration this is your $m.

Array
(
    [0] => Array
        (
            [0] => <img>
            [1] => <img>
            [2] => <img>
            [3] => <img>
        )

)

The count only counts the 0 index, so you get 1.

Answer:

You can use code

<?php
$page="<img><img><img><img>";
preg_match_all("/<img>/",$page,$m);
echo count($m[0]);
?>

Or this is the alternative

<?php
$page="<img><img><img><img>";
$words = substr_count($page, '<img>');
print_r($words);
?>