简体   繁体   中英

Counting items of a rendered menu - PHP/Regex/XPath

Guys, I need some help! I have a fully rendered menu (a safe html output)... and I need the number of <li> ONLY of its first level... example:

<li><a>first</a></li>
<li><a>first</a></li>
<li>
  <a>first</a>
  <ul>
    <li><a>second</a></li>
    <li>
      <a>second</a>
      <ul>
        <li><a>third</a></li>
      </ul>
    </li>
  </ul>
</li>
<li><a>first</a></li>
<li>
  <a>first</a>
  <ul>
    <li><a>second</a></li>
    <li><a>second</a></li>
  </ul>
</li>

So the result should be 5 items...

note: at this moment, the first level is not wrapped by a <ul> yet... so this might help a regex... I believe it can be done using a XPath query as well... but :(

If possible I would like to understand the 2 approaches... :D

thanks!!!

Lets say that you are counting primary li 's inside a <div> tag:

you will be trying this:

$string = "<div><li><a>first</a></li><li><a>first</a></li><li><a>first</a><ul><li><a>second</a></li><li><a>second</a><ul><li><a>third</a></li></ul></li></ul></li><li><a>first</a></li><li><a>first</a><ul><li><a>second</a></li><li><a>second</a></li></ul></li></div>";

$xml = new SimpleXMLElement($string);

/* Search for <div><li> */
$result = $xml->xpath('/div/li');
echo count($result);

will print:

5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM