【问题标题】:php, parse in a ordered HTML list and edit the text in the <li>st without affecting the surrounding HTML tagsphp,解析有序的 HTML 列表并编辑 <li>st 中的文本,而不影响周围的 HTML 标签
【发布时间】:2020-06-12 13:37:16
【问题描述】:

我正在尝试使用 PHP 解析 HTML 列表,然后读取列表的内容(例如儿童和年轻人、居民、专业人士)和标签,在末尾附加一个“/”列表中的每一位文本(最后一项除外),然后输出,而不编辑任何周围的 HTML 标记。

目前我已经在列表中读取并附加了“/”,但我在此过程中删除了周围的标签,是否有人对执行此操作的方法或我应该使用的任何功能有任何建议?谢谢

<ol class="breadcrumb">
        <li class="inline odd first" itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb"><a href="https://my.northtyneside.gov.uk/category/75/residents" itemprop="url"><span itemprop="title">Residents</span></a></li> 
        <li class="inline even" itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb"><a href="https://my.northtyneside.gov.uk/category/175/children-and-young-people" itemprop="url"><span itemprop="title">Children and young people</span></a></li> 
        <li class="inline odd last" itemscope="" itemtype="http://data-vocabulary.org/Breadcrumb"><span itemprop="title">Professionals</span></li>
    </ol>

    <?php

    function injectSlashes($breadcrumb){

        $doc = new DOMDocument();
        $doc->loadHTML($breadcrumb);
        $liList = $doc->getElementsByTagName('li');
        $liValues = array();
        foreach ($liList as $li) {
            $liValues[] = $li->nodeValue;
        }

        $correctBreadcrumb = implode("<span aria-hidden=\"true\">/</span>",$liValues);

        return $correctBreadcrumb;
    }
?>

【问题讨论】:

  • 你想要&lt;li&gt;项目中的所有标签吗?
  • 我希望所有的标签都被返回是的(基本上所有的 html 并且只在文本项的末尾添加一个'/',除了最后一个)

标签: php html list parsing


【解决方案1】:

一个简单的解决方案是更改每个项目存储的数据。

目前,您使用

$liValues[] = $li->nodeValue;

正如您所发现的,它只是项目的文本。

要存储 HTML,您需要使用 saveHTML()。通常这可能是一个文档片段,但您可以将其简化为&lt;li&gt; 标记中的第一个子元素...

$liValues[] = $doc->saveHTML($li->firstChild);

如果需要保留&lt;ol&gt;标签,就比较复杂了。此代码提取标签并仅输出该内容,类似于

<ol class="breadcrumb"></ol>

然后它像以前一样创建面包屑并通过将&gt;&lt;替换为&gt;面包屑&lt;来插入它...

function injectSlashes($breadcrumb){
    $doc = new DOMDocument();
    $doc->loadHTML($breadcrumb);
    // Extract the ol
    $ol = $doc->getElementsByTagName('ol')[0];
    // Output the HTML for just the ol tag
    $olText = $doc->saveHTML($ol->cloneNode());
    $liList = $doc->getElementsByTagName('li');
    $liValues = array();
    foreach ($liList as $li) {
        $liValues[] = $doc->saveHTML($li->firstChild);
    }

    $list = implode("<span aria-hidden=\"true\">/</span>",$liValues);
    // Insert the breadcrumbs in the empty ol tag from above
    $correctBreadcrumb = str_replace("><", ">".$list."<", $olText);
    return $correctBreadcrumb;
}

【讨论】:

  • 这适用于
  • 标签谢谢,但我意识到我的问题措辞不当,我想在返回函数时返回包括
      标签在内的整个列表
  • 是的,奈杰尔,谢谢你,我一直坚持这一天,谢谢!
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签