【问题标题】:Symfony 2 Dom Crawler: how to get only text() in ElementSymfony 2 Dom Crawler:如何在 Element 中仅获取 text()
【发布时间】:2015-07-18 22:28:01
【问题描述】:

使用 Dom Crawler 只获取文本(不带标签)。

$html = EOT<<<
  <div class="coucu">
    Get Description <span>Coucu</span>
  </div>
EOT;

$crawler = new Crawler($html);
$crawler = $crawler->filter('.coucu')->first()->text();

输出: 获取描述 Coucu

我想输出(仅): 获取描述

更新:

我找到了一个解决方案:(但这确实是一个糟糕的解决方案)

...
$html = $crawler->filter('.coucu')->html();
// use strip_tags_content in https://php.net/strip_tags
$html = strip_tags_content($html,'span');

【问题讨论】:

  • 不,我没有使用 jQuery
  • 我不认为有这种方法,但你可以尝试 $text = $crawler->filter('.coucu')->first()->extract(array('_text '));我相信它会返回相同的结果,但仍然值得一试
  • 我使用了提取函数()。但这行不通。
  • 我猜strip_tags_content 来自gist.github.com/marcanuy/7651298。我个人不喜欢 HTML 的正则表达式,它们会导致坏事 (stackoverflow.com/questions/590747/…)。

标签: symfony domcrawler


【解决方案1】:

遇到了同样的情况。我最终选择了:

$html = $crawler->filter('.coucu')->html();
$html = explode("<span", $html);
echo trim($html[0]);

【讨论】:

    【解决方案2】:

    根据您问题中的标准,我认为最好将您的 CSS 选择器修改为:$crawler = $crawler-&gt;filter('div.coucu &gt; span')

    从那里你可以去$span_text = $crawler-&gt;text();

    或者为了简化事情:$text = $crawler-&gt;filter('div.coucu &gt; span')-&gt;text();

    text() method 返回列表中第一项的值。

    【讨论】:

    • 我想得到“Get Description Coucu”。
    【解决方案3】:
    function extractCurrentText(Crawler $crawler)
    {
      $clone = new Crawler();
      $clone->addHTMLContent("<body><div>" . $crawler->html() . "</div></body>", "UTF-8");
      $clone->filter("div")->children()->each(function(Crawler $child) {
        $node = $child->getNode(0);
        $node->parentNode->removeChild($node);
      });
      return $clone->text();
    }
    

    【讨论】:

      【解决方案4】:

      基于正则表达式去除 HTML 的 HTML 删除解决方案(坏主意 Using regular expressions to parse HTML: why not?),并且爆炸解决方案是有限的。

      我想出了不同之处:获取所有文本,然后使用 str_replace 删除非自己的文本。

      【讨论】:

        【解决方案5】:

        这很好用,没有 hacky 变通办法:

        $crawler->filter('.coucu')->children()->each(function (Crawler $crawler) {
            $crawler->getNode(0)->parentNode->removeChild($crawler->getNode(0));
        });
        $crawler->text(); // Get Description
        

        【讨论】:

          【解决方案6】:
          $div = $crawler->filter('.coucu')->html();
          $span = $crawler->filter('.coucu > span')->html();
          $text = strip_tags(str_replace($span,'',$div));
          

          【讨论】:

            猜你喜欢
            • 2012-10-18
            • 1970-01-01
            • 2021-04-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-04-06
            • 1970-01-01
            相关资源
            最近更新 更多