PHP简单的html dom解析器 - 查找单词
问题描述:
我使用PHP简单的html dom解析器库,我只想用[WORD FIND HERE]替换所有'manteau'单词。这是我的代码,下面的代码不适用于不在标签中的单词。它只能在强标签内使用“manteau”这个词。如何解析所有节点文本?PHP简单的html dom解析器 - 查找单词
注意: str_replace不是解决方案。 DOM PARSER需要在这里使用。我不想选择锚点或图片标签中的单词。
<?php
require_once '../simple_html_dom.php';
$html = new simple_html_dom();
$html = str_get_html('Un manteau permet de tenir chaud. Ce n\'est pas
un porte-manteau. Venez découvrir le <a href="pages/manteau">nouveau
manteau</a> du porte-manteau.
<h1>Tout savoir sur le Manteau</h1>
<p>
Le <strong>manteau</strong> est un élèment important à ne pas négliger.
Pas comme le porte-manteau.
</p>
<img src="path-to-images-manteau" title="Le manteau est beau">');
$nodes = $html->find('*');
foreach($nodes as $node) {
if(strpos($node->innertext, 'manteau') !== false) {
if($node->tag != 'a')
$node->innertext = '[WORD FIND HERE]';
}
}
}
echo $html->outertext;
?>
答
改为使用str_replace();
! http://php.net/manual/en/function.str-replace.php
$html = str_replace('manteau', 'rubber chicken', $html);
echo $html;
看到它在这里工作; https://3v4l.org/GRfji
+0
感谢您的回答,但str_replace不是解决方案。 dom操作需要在这里使用。我不想选择锚点或图片标记中的单词。 –
答
也许这是一个选项,可以排除您不想更改的标签。
例如:
<?php
require_once '../simple_html_dom.php';
$html = new simple_html_dom();
$html = str_get_html('Un manteau permet de tenir chaud. Ce n\'est pas
un porte-manteau. Venez découvrir le <a href="pages/manteau">nouveau
manteau</a> du porte-manteau.
<h1>Tout savoir sur le Manteau</h1>
<p>
Le <strong>manteau</strong> est un élèment important à ne pas négliger.
Pas comme le porte-manteau.
</p>
<img src="path-to-images-manteau" title="Le manteau est beau">');
$nodes = $html->find('*');
$tagsToExclude = [
"a",
"img"
];
foreach($nodes as $node) {
if (!in_array($node->tag, $tagsToExclude)) {
if(strpos($node->innertext, 'manteau') !== false) {
$node->innertext = str_replace("manteau", '[WORD FIND HERE]', $node->innertext);
}
}
}
echo $html->outertext;
?>
解析听起来有点像这里只是更换字矫枉过正。为什么不使用'str_replace' – lumio
dom操作需要在这里使用。我不想选择锚定字或图像标记 –
我明白了。那么使用解析是个好主意。我想你也可以使用正则表达式。 (* s/a矫枉过正/矫枉过正/) – lumio