-->

纯文本简单的HTML DOM str_replace函数(Simple HTML DOM str_r

2019-10-29 20:38发布

我想创造的东西在那里它将改变网页上的所有文本,并重新它输出给用户。 这将改变在一个数据库中预定义的话。

我使用http://simplehtmldom.sourceforge.net作为我的HTML解析器。 我想待办事项是要改变只有测试里面的标签,但没有标签。 我认为这会工作,如果我赞同了$e->plaintext它会工作,但那么它是不是风格。

<?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;
?>

提前致谢!

PS:以前我是使用preg_replace_callback但有人建议我用这个。

Answer 1:

逐个更换文本节点的内容,而不是一次改变整个文件的文本:

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


文章来源: Simple HTML DOM str_replace on plain text