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?
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
.
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);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With