gpt4 book ai didi

php - 纯文本上的简单 HTML DOM str_replace

转载 作者:行者123 更新时间:2023-11-30 01:00:25 26 4
gpt4 key购买 nike

我正在尝试创建一些东西,它将更改网页上的所有文本并将其重新输出给用户。它将改变数据库中预定义的单词。

我正在使用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;
?>

提前致谢!

p.s.:之前我使用preg_replace_callback,但有人建议我使用这个。

最佳答案

单独替换每个文本节点的内容,而不是一次更改整个文件的文本:

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

关于php - 纯文本上的简单 HTML DOM str_replace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20180554/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com