问题
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