Reputation: 115
I'm trying to count all <img>
tags inside a string line by line but cant figure it out.
i've already made to split the string line by line, then count the <img>
tags after it.
Example :
$string = "
some text <img src="" /> some text <img src="" /> some text <img src="" /> some text \n
some text <img src="" /> some text `<img src="" /> some text <img src="" /> some text ";
now my code is first to split it line by line
$array = explode("\n", $string);
now count how many <img>
tags are there in the first line of var string.
$first_line = $array['0'];
i was using preg_match() to get match for img tags.
$img_line = preg_match("#<img.+>#U", $array['0']);
echo count($img_line);
this wont work for me, in the $string there are 3 <img src="">
per line but my code gives me only 1.
any hint or tips are highly appreciated.
Upvotes: 1
Views: 1521
Reputation: 7263
<?php
$string = 'some text <img src="" /> some text <img src="" /> some text <img src="" /> some text \n
some text <img src="" /> some text `<img src="" /> some text <img src="" /> some text ';
$count = preg_match_all("/<img/is", $string, $matches);
echo $count;
?>
Upvotes: 0
Reputation: 5037
You can try the following code:
<?php
$string = <<<TXT
some text <img src="" /> some text <img src="" /> some text <img src="" /> some text
some text <img src="" /> some text <img src="" /> some text <img src="" /> some text
TXT;
$lines = explode("\n", $string);
// For each line
$count = array_map(function ($v) {
// If one or more img tag are found
if (preg_match_all('#<img [^>]*>#i', $v, $matches, PREG_SET_ORDER)) {
// We return the count of tags.
return count($matches);
}
}, $lines);
/*
Array
(
[0] => 3 // Line 1
[1] => 3 // Line 2
)
*/
print_r($count);
Here, PREG_SET_ORDER
stores the results in a single level (first capture to index $matches[0]
, second capture to index $matches[1]
). Thus, we can easily retrieve the number of catches.
Upvotes: 0
Reputation: 115
Got it..
After splitting the string per line.
$first_line = $array['0'];
$match = preg_match_all("#<img.+>#U", $first_line, $matches);
print_r($matches);
echo count($matches['0']);
the code above will return this..
Array
(
[0] => Array
(
[0] =>
[1] =>
[2] =>
)
)
3
Upvotes: 0
Reputation: 1373
If you do a simple explode
line by line, this will give you the count:
$explode = explode('<img ', $array[0]);
echo count($explode);
Upvotes: 1