Count number of <li> tags in a <ul> on serverside using PHP
I have a < ul > with some < li >(s). I want to count the number of these <开发者_JAVA技巧; li>s on server side. And if this number qualifies a given condition then i would like to add some more < li> elements to this < ul>. Can someone please help me with this ?
First a simple example using php's DOM module and XPath
$s = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><head><title>...</title></head><body>
<ul>
<li>1</li><li>2</li>
</ul>
<ul>
<li>1</li><li>2</li><li>3</li>
</ul>
<ul>
<li>x</li><li>y</li>
</ul>
</body></html>';
$doc = new DOMDocument;
$doc->loadhtml($s);
$xpath = new DOMXPath($doc);
foreach( $xpath->query('//ul[ count(li)<3 ]') as $ul ) {
$li = $doc->createElement('li', 'abc...xyz');
$ul->appendChild($li);
}
echo $doc->savehtml();
and then an oversimplified example of what I meant by "And that function can't include the extra data as well?"
echo firstFunction(array('a'), 'secondFunction');
function firstFunction($arrData, $fnFill=null) {
$rv = '';
$counter = 0;
foreach($arrData as $e) {
$counter += 1;
$rv .= '<li>'.htmlspecialchars($e).'</li>';
}
if ( 4 > $counter && !is_null($fnFill)) {
// oh no. Not enough elements. Let's call $fnFill(), it provides some filler material
$rv .= $fnFill();
}
return $rv;
}
// providing extra li elements
function secondFunction() {
return '<li>x</li><li>y</li><li>z</li>';
}
Use PHP's DOM library, or look up Simple DOM Parser. They both have everything you need for manipulating and searching HTML to the extent of your question
精彩评论