【问题标题】:get before and after dom element php获取dom元素php之前和之后
【发布时间】:2015-08-22 05:32:15
【问题描述】:

我想在一个元素之前和之后获取单词,我可以用一个小函数来做,但是如果它以这个元素开始或结束,我会卡住

我的元素:a[id=2] 我的文字:

bla bla bla bla <a id="2">My link</a> blu blu blu

根据这个问题extract part of a string before and after a word 我创建了一个小脚本来获取这样的链接:

$left = substr($tab[0], -10);
$right = substr($right, 1, 10);
$text = "... $left $query $right ...";

它返回:

'... bla bla <a id="2">My link</a> blu blu ...'

但是当我搜索时:

<a id="2">My link</a> bla bla bla bla blu blu blu
or
bla bla bla bla blu blu blu <a id="2">My link</a>

explode() 函数只返回一个数组,因为在分隔符之前/之后没有任何内容...我有错误“未定义偏移量:1

你有什么解决办法吗?

【问题讨论】:

  • 你知道父元素吗?还是每次都不一样?
  • explode() 代码?这个答案stackoverflow.com/a/12629211/861704怎么样?
  • @splash58 父级每次都不一样
  • @Jigar 和正则表达式我有同样的问题,如果它是在开始或结束 $r = preg_replace('/(.+)?([^\s]+.{0 ,30}'.$node->text().'.{0,30}[^\s]+)(.+)?/', '... $2 ...', $node->saveHTML ());但如果它在中间就可以正常工作......
  • @Samir 在我的回答中我找到了&lt;a id=2 并接受了它的父母。

标签: php laravel explode


【解决方案1】:

对于那些感兴趣的人,我找到了一个适合我的解决方案,无论查询是在开始中间还是在字符串末尾。

function extract_before_after($str, $query)
{
    $expl = explode($query, $str);

    // if $query is at the begin
    if(isset($expl[0]) && strlen($expl[0]) === 0){
        $before = '...';
        $after = substr($expl[1], 0, 100) . '...';
        $new_text = $before . ' ' . $query . ' ' . $after;
    }
    // if $query is at the end
    elseif(isset($expl[1]) && strlen($expl[1]) === 0){
        $before = substr($expl[0], -100) . '...';
        $after = '...';
        $new_text = $before . ' ' . $query . ' ' . $after;
    }
    // if $query is in middle
    elseif(
        (isset($expl[0]) && strlen($expl[0]) > 0)
        && (isset($expl[1]) && strlen($expl[1]) > 0)
    ){
        $before = '...' . substr($expl[0], -100);
        $after = substr($expl[1], 0, 100) . '...';
        $new_text = $before . ' ' . $query . ' ' . $after;
    }
    // if $query not found...
    else{
        $new_text = '... nothing ...';
    }

    return $new_text;
}

感谢您的有用帮助

【讨论】:

    【解决方案2】:

    假设,$dom 包含 DomDocument。然后创建xpath - 获取标签&lt;a id=2...的父元素的文本如果parent只包装一个a标签而不是$text将是包含两个对象的数组 - 之前的文本和之后的文本,如果包含更多元素数组会有很多部分,但你可以将它们组合起来。

    $xpath = new DOMXpath($dom);
    $texts = $xpath->query('//a[@id="2"]/../text()');
    $text = array();
    foreach($texts as $t) $text[] = $t->nodeValue;
    echo implode(' ', $text);
    

    【讨论】:

    • 是的,它对我来说很好用!但是当我通过链接开始或结束时出现同样的问题, text[] 只返回一个数组......一个解决方案应该(顺便说一下我使用这个库:github.com/wasinger/htmlpagedom 那就是使用 Symfony domcrawler 来获取父级)一个解决方案要知道链接是在开头还是结尾,并通过添加空白文本来生成缺失的部分?你怎么看?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    相关资源
    最近更新 更多