php - 如何用纯文本替换多个 img 元素?

标签 php html dom domdocument

我想创建一个输出文本过滤器来替换所有 <img> DOM 中带有以下文本“no images allowed ”的元素。

即:如果用户创建此 HTML 标记:

<p><img src="/image.jpg" /></p>

呈现以下 HTML:

<p>no images allowed</p>

请注意,我无法使用 preg_replace 。问题被简化了,我需要解析 DOM 以找到不允许的图像。

感谢this answer ,我发现getElementsByTagName()返回“live”迭代器,所以你需要两个步骤,所以我有这个:

foreach ($elements as $element) {
  $domArray[] = $element;
  $src= $element->getAttribute('src');
  $frag= $dom->createElement('p');
  $frag->nodeValue = 'no images allowed';
  $element->parentNode->appendChild($frag);
}
// loop through the array and delete each node
$nodes = iterator_to_array($dom->getElementsByTagName('img'));
foreach ($nodes as $node) {
  $node->parentNode->removeChild($node);
}
$newtext = $dom->saveHTML();

几乎做我想做的事,但我明白了:

<p><p>no images allowed</p></p>

最佳答案

我将使用 xpath 获取元素,然后替换为新创建的文本节点。

$xp = new DOMXPath($dom);
$elements = $xp->query('//img');
foreach ($elements as $element) {
  $frag= $dom->createTextNode('no images allowed');
  $element->parentNode->insertBefore($frag, $element);
  $element->parentNode->removeChild($element);
}
echo $dom->saveHtml();

此处演示:http://codepad.org/w9uj0ez9

关于php - 如何用纯文本替换多个 img 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46745261/

相关文章:

php - Symfony2 : disable Twig cache

javascript - HTML数据属性IE6支持

google-chrome - 我应该使用MutationRecord.oldValue吗?

Java HTML 对象

php - javascript和php中印度车号的正则表达式

php - 在 Mac 上转换为使用 excel 制作的 utf-8 csv 文件时出现问题

javascript - 无法从 Firefox 上的提交按钮中删除虚线边框

html - 一个高的 div 在桌面上紧挨着两个较短的 div,在移动设备上使用 Bootstrap 4 堆叠

javascript - 如何在 SVG 中沿设定方向移动线条

php - XPath仅从元素内获取文本(PHP)