Reputation: 1956
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.
Upvotes: 3
Views: 4282
Reputation: 122
Try this, it should work in almost all cases:
<?php
$t='<div id="list">
<ul>
<li class="some classes">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>';
$list_array=explode("</li>",$t);
echo "total in list = ".count($list_array);
?>
Upvotes: 1
Reputation: 71548
<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.
Upvotes: 4