3

I'm trying to return the count of a list. The list looks like:

<div id="list">
    <ul>
        <li class="some classes">1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
    </ul>
</div>

I just can't figure out how to get a count of the li tags. I don't care about the contents, just the count. This is what I have:

preg_match_all('!<div id="list">.*?<li.*?>.*?</li>.*?</ul>!', $content, $matches);

Ugly I know, and I only receive one match when I count($matches[0]);

Can anyone point out what I'm doing wrong and/ or why?

Thanks

EDIT: I know parsing HTML with regex is bad, but I have little choice in the matter right now.

Community
  • 1
  • 1
James
  • 1,950
  • 3
  • 22
  • 39
  • 1
    Obligatory: http://stackoverflow.com/a/1732454/722762 TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ – Halcyon Sep 16 '13 at 15:53
  • Oh yeah, I forgot to mention I have no choice right now... but thanks for your concern :P – James Sep 16 '13 at 15:54

2 Answers2

4
<div id="list">.*?<li.*?>.*?</li>.*?</ul>
                                 ^^^

The part I'm pointing out is consuming all the characters until </ul> (even the <li> parts). After consuming them, there no more to match and it ends here, giving only one match.

Jerry
  • 70,495
  • 13
  • 100
  • 144
  • If you want to find a solution for that, you might use the regex [here](http://www.regex101.com/r/cZ3dB1) which counts all the `
  • ` within a set of `
      `
  • – Jerry Sep 16 '13 at 16:08