代码之家  ›  专栏  ›  技术社区  ›  Ricardo

xpath remove并将多行文本推送到一个数组中

  •  0
  • Ricardo  · 技术社区  · 7 年前

    我已经潜伏了好几个小时的StackOverflow寻找可能的答案,尽管我找到了一些解决方案,但在我的案例中没有一个是有效的。

    我需要获取该分区的文本并通过 foreach 循环以最终为每个DIV内容创建一个新的数据库记录。

    在我面对多行内容和 <br> 标签。

    我尝试过:

    $quotes = $finder->query("//*[contains(@class, normalize-space('$quote'))]//text()");
    

    但看起来不像 normalize-space() 有任何效果,因为它不会将整个文本推送到一个数组中,而是在 <BR> 相反。

    更多代码:

    $quotes = $finder->query("//*[contains(@class, normalize-space('$quote'))]//text()");
    $authors = $finder->query("//*[starts-with(@class,'$author')]/child::a");
    
        foreach ($quotes as $key => $quote) {
            {
                $quote = trim($quote->textContent);
                $dataArr[] = $quote;
                $authorName = preg_split("/[\s,-,@]+/", $authors[$key]->textContent);
    
                if (count($authorName) < 5) {
                    $authorName = $authorName[1];
                } else if (count($authorName) > 5) {
                    $authorName = $authorName[1] . ' ' . $authorName[2] . ' ' . $authorName[3];
                } else if (count($authorName) > 6) {
                    $authorName = $authorName[1] . ' ' . $authorName[2] . ' ' . $authorName[3] . ' ' . $authorName[4];
                } else {
                    $authorName = $authorName[1] . ' ' . $authorName[2];
                }
                array_push($dataArr, $authorName);
        }
    

    正确提取的HTML结构:

    <div class="b-list-quote2__item "><a href="/" class="b-list-quote2__item-text js-quote-text">
        A random quote here...
    </a><div class="b-list-quote2__item-category">
        <a href="/quotes/albert-einshtein?q=17856">Albert Einstein</a>
    

    在本例中,我得到一个带有引号和作者的数组,稍后我将其分为2块,并在其他函数中使用

    [0] => A random quote here... [1] => Albert Einstein

    我遇到的HTML结构问题是:

    <div class="b-list-quote2__item "><a href="/" class="b-list-quote2__item-text js-quote-text" style="position: relative; max-height: none;">
        Quote line 0,
        <br>Quote line 1,
        <br>Quote line 2,
        <br>Quote line 3,
    </a><div class="b-list-quote2__item-category">
        <a href="/quotes/karmelita-kruglaia?q=249176">Tesla</a>
    

    在这种情况下,每行文本都会添加一个新的数组项,类似于

    [0] => Quote line 0 [1] => Quote line 1 [2] => Quote line 2 [3] => Quote line 3

    数组中没有“author”,在本例中应为“tesla”。

    一个好的数组应该是什么样子的:

    [0] => Quote line 0 Quote line 1 Quote line 2 Quote line 3 [1] => Tesla

    1 回复  |  直到 7 年前
        1
  •  1
  •   Nigel Ren    7 年前

    当运行xpath查询时,最后一部分要求分别提取每个文本节点(即 //text() 位在表达式的末尾)。相反,您只需要整个元素的文本。对于dom,每段文本都是一个单独的节点,因此

    Quote line 0,
    <br>Quote line 1,
    

    是两个单独的文本节点。您的查询正在将此(如您所发现的)检索为2个元素。

    所以使用

    $quotes = $finder->query("//*[contains(@class, normalize-space('$quote'))]");
    

    应该给你所有的文本。文本中会有换行符,所以您可以…

    $dataArr[] = str_replace("\n", " ", $quote);
    
    推荐文章