簡體   English   中英

如何基於HTML標簽更新文本

[英]How update text based on HTML tags

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

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

我想在標簽的<div>...</div>周圍將單詞“ 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標簽。 我該如何預防?

如果正確編寫查詢,則可以使用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() );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM