Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count length of images in a string

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?

like image 419
Amit Verma Avatar asked Dec 25 '15 04:12

Amit Verma


2 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.

like image 187
chris85 Avatar answered Nov 12 '22 11:11

chris85


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);
?>
like image 3
Wilianto Indrawan Avatar answered Nov 12 '22 09:11

Wilianto Indrawan