Simple HTML DOM str_replace on plain text

拥有回忆 提交于 2019-12-25 02:09:59

问题


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:


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();


来源:https://stackoverflow.com/questions/20180554/simple-html-dom-str-replace-on-plain-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!