douwei1128 2013-11-24 20:26
浏览 46
已采纳

纯文本上的简单HTML DOM str_replace

I am trying to create something where it will change all of the text on a webpage and re output it to the user. It will be changing words predefined in a database.

I am using http://simplehtmldom.sourceforge.net as my HTML parser. What i want todo is to change only the test inside of tags but not the tags. I thought this would work, If i echo out $e->plaintext it will work but then it isn't styled.

<?php
// example of how to modify HTML contents
include('../simple_html_dom.php');

// get DOM from URL or file
$html = file_get_html('http://example.com/');

$e = $html->find("html", 0);

$text = $e->plaintext;

$con = mysqli_connect("localhost","root","root","Words");
$result = mysqli_query($con,"SELECT * FROM Wordsweb");

//replace all words
$English = array();
$Simple = array();

while ($row =  mysqli_fetch_array($result)){
    $English[] = $row['English'];
    $Simple[] = $row['Simple'];
}

$e->plaintext = str_replace($English, $Simple,$e->plaintext);
echo $e;
?>

Thanks in advance!

p.s.: previously i was using preg_replace_callback but i was advised to use this.

  • 写回答

1条回答 默认 最新

  • douji3426 2013-11-26 00:07
    关注

    Replace the contents of each text node individually, rather than changing the text of the whole file at once:

    <?php
    
    // load the HTML document
    $doc = new DOMDocument;
    @$doc->loadHTMLFile('https://en.wikipedia.org/wiki/Banana');
    
    // select all the text nodes
    $xpath = new DOMXPath($doc);
    $nodes = $xpath->query('//text()');
    
    // replace text in each text node
    $english = array('banana', 'bananas');
    $simple = array('yello', 'yellos');
    
    foreach ($nodes as $node) {
        $node->nodeValue = str_replace($english, $simple, $node->nodeValue);
    }
    
    print $doc->saveHTML();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错