我必须从带有可能子列表的列表中创建一个菜单。从一个简单的我想创建一个兼容的引导菜单所以从这样的代码:
<ul>
<li>Link 1</li>
<li>Link 2
<ul>
<li>Sublink A</li>
<li>Sublink B</li>
</ul>
</li>
<li>Link 3
<ul>
<li>Sublink C</li>
</ul>
</li>
</ul>
我必须创建这个:
array(
[0] => array(
[id] => 1,
[nome] => 'Link 1',
[parent] => NULL,
),
[1] => array(
[id] => 2,
[nome] => 'Link 2',
[parent] => NULL,
),
[2] => array(
[id] => 3,
[nome] => 'Sublink A',
[parent] => 2
),
[3] => array(
[id] => 4,
[nome] => 'Sublink B',
[parent] => 2
),
[4] => array(
[id] => 5,
[nome] => 'Link 3',
[parent] => NULL
),
[5] => array(
[id] => 6,
[nome] => 'Sublink C',
[parent] => 3
)
)
最后,取回这个:
<ul class="nav navbar-nav">
<li><a class="primary" href="link_1.html">Link 1</a></li>
<li class="dropdown">
<a href="#" class="primary dropdown-toggle" data-toggle="dropdown">Link 2</a>
<ul class="dropdown-menu">
<li><a href="sublink_a.html">Sublink A</a></li>
<li><a href="sublink_b.html">Sublink B</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="primary dropdown-toggle" data-toggle="dropdown">Link 3</a>
<ul class="dropdown-menu">
<li><a href="sublink_c.html">Sublink C</a></li>
</ul>
</li>
</ul>
条件是:如果
我使用这段代码,但它只用于一个简单的列表,而不是嵌套列表。
<?php
$currentPage = "";
$contents = "<ul>
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
</ul>";
// remove width, height, style
$contents = preg_replace('/(width|height|style|target)="[^"]+"/i', "", $contents);
// remove spaces form li
$contents = str_replace(array('<li >',' <li >'),"<li>",$contents);
// remove ul/ol tag and tabs
$contents = str_replace(array('\t','<ul>','<ul >','</ul>','<ol>','<ol >','</ol>'),"",$contents);
$arrNavTopList = explode("\n",trim($contents));
echo "<h4>Array:</h4>\n";
print_r($arrNavTopList);
echo "<hr>\n<h4>List:</h4>\n";
$totNavTopList = count($arrNavTopList);
if($totNavTopList>0){
echo '<ul class="nav navbar-nav">'."\n";
$countNtL=1;
foreach($arrNavTopList as $pagename) {
$pagename = str_replace("\t","",$pagename);
preg_match_all("(<li>(.*?)</li>)", $pagename, $arrLinkList);
$linktopage = $arrLinkList[1][0];
if(
strtolower($linktopage)==strtolower(str_replace("_"," ",$currentPage)) ||
strtolower($linktopage)=="home" && !(strpos($currentPage,"^")===FALSE)
) {
$active=' class="active"';
} else {
$active='';
}
echo '<li'.$active.'>';
if (strstr($linktopage,"http") || strstr($linktopage,"target")) {
$linktopage = preg_replace('/(style|target)="[^"]+"/i', "", $linktopage);
$linktopage = str_replace('<a','<a rel="external nofollow" class="_blank"',$linktopage);
echo $linktopage;
} else {
if(strtolower($linktopage)=="home" || strtolower($linktopage)=="home page") {
echo '<a href="/">'.htmlentities($linktopage).'</a>';
} else {
echo '<a href="'.str_replace(" ","_",strtolower($linktopage)).'">'.htmlentities($linktopage).'</a>';
}
}
echo '</li>'."\n";
$countNtL++;
}
echo '</ul>'."\n";
}
?>