PHP - number of li elements inside ul

I am looking for a way to count dynamic li elements inside ul in php (not js).

For instance:

<ul> <li> lorem </li> <li> ipsum </li> <li> dolor </li> <li> sit </li> </ul> 

will return me the number 4 . (am I too stupid to use the correct code here?)

Is there any way to do this in php?

Thanks in advance!

EDIT:

The markup is created by the cms system, the account must be placed in front of the list inside the template file.

+6
source share
4 answers

You can make a very simple Subscript for <li> (or -li- ) on this line, and it will return the number of elements.


Edit:

 $count = substr_count($html,'<li>'); //where $html holds your piece of HTML. 
+11
source

Assuming this HTML is not output by you (otherwise it must be trivial to count the number of elements), you can use PHP DOMDocument .

 $dom = new DOMDocument; $dom->loadHTML($str); foreach($dom->getElementsByTagName('ul') as $ul) { $count = $ul->getElementsByTagName('li')->length; var_dump($count); } 

CodePad

This code will count the number of li elements in each ul element. If you don't need separate ul elements, just use $dom->getElementsByTagName('li')->length .

+6
source

Your answer lies with DOMDocument .

For instance:

 $dom = new DOMDocument(); $dom -> loadHTML("<ul><li></li><li></li></ul>"); $li = $dom->getElementsByTagName("li"); foreach ($li as $li_c){ $i++; } echo $i; 
+3
source

Use the PHP DOM library or take a look at Simple DOM Parser. It contains an HTML search.

0
source

Source: https://habr.com/ru/post/897206/


All Articles