Count length of images in a string
Asked Answered
O

2

7

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?

Oncoming answered 25/12, 2015 at 4:37 Comment(1)
If it is a fixed value, you can use substr_count()Alkane
S
10

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.

Space answered 25/12, 2015 at 4:59 Comment(0)
C
3

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);
?>
Citral answered 25/12, 2015 at 4:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.