tags:

views:

28

answers:

1

Hi there! :D

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!!!

+1  A: 

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
Garis Suero
@Garis Suero: Also `count(/div/li)` is a valid XPath expression wich evaluete to `5`.
Alejandro
yeap! thank you very much dude! :Dnow... do you have any idea about the performance of a XPath query? should I put at first on my list before building a regex?thx again!
Wil