纯文本上的简单HTML DOM str_replace [英] Simple HTML DOM str_replace on plain text

查看:188
本文介绍了纯文本上的简单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.

我正在使用 http ://simplehtmldom.sourceforge.net 作为我的HTML解析器。我想要的只是改变标签内部的测试,而不是标签。我以为这可以工作,如果我回应 $ e-> plaintext ,它将工作,但后来没有样式。

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

提前感谢!

> ps :以前我正在使用 preg_replace_callback ,但建议您使用此。

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

推荐答案

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

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

这篇关于纯文本上的简单HTML DOM str_replace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆