删除<a>与preg_replace的链接,但保留<img>图像


Removing <a> links with preg_replace but keeping <img> images inside

我正在使用:

$this->tresc[$i][description]=preg_replace("/'<a .*'>.*'<'/a'>/i", "", $this->tresc[$i][description]);

以删除链接。

有时链接内部有我想保留的图像:

<a href="http://www.domain.com/page.php"><img src="http://domain.com/image.jpg" alt="​Image" align="left" /></a>

这可能吗?现在,所有<a></a>都被移除了。

PHP的strip_tags()函数允许您指定要保留的HTML实体。

http://php.net/manual/en/function.strip-tags.php

您可以使用可选的第二个参数来指定应该 不被剥离。

strip_tags($rssContent, '<img>');

这应该删除/清理所有 HTML 元素,而不保留 <img> 标记。


PHP 文档中该页面的注释部分还包含大量可能对您有用的有用函数。 我建议通读它们。
这个特别看起来很有趣。

我这样做了:

$this->tresc[$i][description]=preg_replace("/<a href='"(.*)'">/i", "",$this->tresc[$i][description]);
$this->tresc[$i][description]=preg_replace("/<'/a'>/i", "",$this->tresc[$i][description]);

但这留下了链接上的文本。