![](/img/trans.png)
[英]Sort Multiple UL and LI elements using jquery UI sortable
[英]Find only first a elements in li (excluding ul elements in li) using simplehtmldom
我正在使用simplehtmldom在網站中查找特定元素。
我的密碼
function strpos_arr($haystack) {
$needle = array('menu', 'nav');
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $what) {
if(($pos = strpos($haystack, $what))!==false)
return true;
}
return false;
}
$first = true;
foreach($html->find('ul') as $ul){
if ( strpos_arr($ul->id) OR strpos_arr($ul->class) ) {
if ( $first )
{
foreach($ul->find('li a') as $li)
{
echo $li.'<br>';
}
$first = false;
}
}
}
?>
此代碼顯示所有li元素中的所有鏈接,包括嵌套在li元素下ul元素內的鏈接。 我只需要回顯li中的main a元素,而不回顯ul subs下嵌套的那些元素。
編輯:
所需的行被標記為“我需要的href”
<ul id="parent">
<li>a href I need<li>
<li>a href I need<li>
<li>a href I need<li>
<li>a href I need<li>
<ul id="sub">
<li>a href I DON'T need<li>
<li>a href I DON'T need<li>
</ul>
<li>a href I need<li>
<li>a href I need<li>
</ul>
我試圖使用CSS選擇器來過濾元素,但是沒有用...所以我使用DOM函數來確保實際元素的父對象是parent
這是一個工作代碼,為您提供所需的li
節點:
$text = '
<ul id="parent">
<li>a href I need</li>
<li>a href I need</li>
<li>a href I need</li>
<li>a href I need</li>
<ul id="sub">
<li>a href I DON\'T need</li>
<li>a href I DON\'T need</li>
</ul>
<li>a href I need</li>
<li>a href I need</li>
</ul>';
//Create a DOM object
$html = new simple_html_dom();
// Load HTML from a string
$html->load($text);
// Find li elmenets within ul tags
$list = $html->find('ul+li');
// Find succeeded
if ($list) {
echo "<br/> Found ". count($list);
// Display output as code
echo "<pre>";
foreach ($list as $key => $elm) {
if($elm->parent()->id == "parent") {
echo htmlentities($elm->outertext);
echo "<hr/>";
}
}
echo "</pre>";
}
else
echo "Find function failed !";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.