Reputation: 71
i'm searching for a way to count dynamic li elements inside an ul in php (not js).
For example:
<ul>
<li> lorem </li>
<li> ipsum </li>
<li> dolor </li>
<li> sit </li>
</ul>
would return me the number 4. (am i too stupid to use proper code here?)
Is there some way to accomplish that in php?
Thanks in advance!
EDIT:
The markup is generated by a cms system, the count should be placed before the list, inside the template file.
Upvotes: 7
Views: 13090
Reputation: 24818
You can do a very simple Substring Count for <li>
(or -li-
) on that string and it would return the number of items.
Edit:
$count = substr_count($html,'<li>'); //where $html holds your piece of HTML.
Upvotes: 12
Reputation: 5615
Your answer lies with DOMDocument.
For example:
$dom = new DOMDocument();
$dom -> loadHTML("<ul><li></li><li></li></ul>");
$li = $dom->getElementsByTagName("li");
foreach ($li as $li_c){
$i++;
}
echo $i;
Upvotes: 4
Reputation: 1734
Use PHP's DOM library, or look up Simple DOM Parser. It contain searches for HTML
Upvotes: 0
Reputation: 490233
Assuming this HTML is not output by you (otherwise it should be trivial to count the number of elements), you could use PHP's DOMDocument.
$dom = new DOMDocument;
$dom->loadHTML($str);
foreach($dom->getElementsByTagName('ul') as $ul) {
$count = $ul->getElementsByTagName('li')->length;
var_dump($count);
}
This code will count the number of li
elements in each ul
element. If you don't care about individual ul
elements, just use $dom->getElementsByTagName('li')->length
.
Upvotes: 6