【问题标题】:How update text based on HTML tags如何根据 HTML 标签更新文本
【发布时间】:2023-03-23 23:54:01
【问题描述】:

我有一个非常基本的例子:

 <div><span>Lorem ipsum dolor sit amet, elit</span>consectetur adipiscing</div>

当标签的&lt;div&gt;...&lt;/div&gt; 出现时,我想将单词“dolor”替换为“some_another_word”。 “dolor”字可以放在div的里面和外面

我当前的代码是下一个:

$html = '<div><span>Lorem ipsum dolor sit amet, elit</span>consectetur adipiscing</div>';

$docs = new \DOMDocument();
$docs->loadHTML( $html );

$els = $docs->getElementsByTagName('*');

foreach ( $els as $node ) {
    if ( 'div' === $node->nodeName ) {
        $node->textContent = str_replace('dolor', 'some_another_word', $node->textContent);
    }
}

var_dump( $docs->saveHTML() );

我的代码的结果是:

<html><body><div>Lorem ipsum some_another_word sit amet, elit consectetur adipiscing</div></body></html>

我丢失了我需要的span 标签。如何预防?

【问题讨论】:

  • spandiv 的子节点。您必须检查您的 div 是否没有子节点 - 然后将其替换为 nodevalue,否则 - 更深入。
  • @u_mulder 提交您的评论作为答案。
  • No) 这真的不是答案,答案应该包含一些代码,但我很懒。

标签: php html-parsing domdocument


【解决方案1】:

如果您正确设计查询,您可以使用XPath 表达式非常精确地定位您希望操作的内容。下面应该给出一个想法,你可以如何应用这个想法。

$html = '<div><span style="color:red">Lorem ipsum dolor sit amet, elit</span>consectetur adipiscing</div>';
$word = 'dolor';
$replace = '#### banana ####';

try{

    libxml_use_internal_errors( true );

    $dom=new DOMDocument;
    $dom->preserveWhiteSpace = false;
    $dom->validateOnParse = false;
    $dom->standalone=true;
    $dom->strictErrorChecking=true;
    $dom->substituteEntities=true;
    $dom->recover=true;
    $dom->formatOutput=false;
    $dom->loadHTML( $html );

    $errors = libxml_get_errors();
    libxml_clear_errors();


    if( !empty( $errors ) ) {
        throw new Exception( implode( PHP_EOL, $errors ) );
    }
    $xp=new DOMXPath( $dom );

    /* The XPath expression */
    $query='//div/span[ contains( text(),"'.$word.'") ]';

    $col=$xp->query( $query );
    if( !empty( $col ) ){
        foreach( $col as $index => $node ){
            $node->nodeValue = str_replace( $word, $replace, $node->nodeValue );
        }

        /* output to browser or save to file */
        echo $dom->saveHTML();  

    } else {
        throw new Exception( sprintf( 'Empty nodelist - XPath query %s failed', $query ) );
    }
    $dom=$xp=null;
}catch( Exception $e ){
    printf( 'Caught Exception -> Trace:%s Message:%s Code:%d', $e->getTraceAsString(), $e->getMessage(), $e->getCode() );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多