如何在没有img src的情况下删除http和https


How to remove http and https without img src

代码:

$str = 'http://www.google.com <img src="http://placehold.it/350x150" />';
$str = preg_replace('/'b(https?):'/'/[-A-Z0-9+&@#'/%?=~_|$!:,.;]*[A-Z0-9+&@#'/%=~_|$]/i', '', $str);
echo $str;

输出:

<img src="" />

我需要这个输出:

<img src="http://placehold.it/350x150" />

我该怎么做?

谢谢你的帮助。

我还认为DOMDocumentDOMXPath是解析HTML标记的首选工具
但就在您的特定情况下,这里有一个使用regexp负查找断言的解决方案:

$str = 'http://www.google.com <img src="http://placehold.it/350x150" /> http://www.google.com.ua';
$str = preg_replace('/(?<!src='")(https|http):'/'/[^'s]+'b/i', '', $str);
print_r($str);   // <img src="http://placehold.it/350x150" />

这将删除所有URL,imgsrc属性

内的URL除外

您的模式

/'b(https?):'/'/[-A-Z0-9+&@#'/%?=~_|$!:,.;]*[A-Z0-9+&@#'/%=~_|$]/i

删除以协议httphttps开头的所有URL(字符串中)。因此,当您将其应用于字符串时,它将删除字符串开头的URL和作为<img>src的URL。因此,您必须在模式的开头使用^

$str = 'http://www.google.com <img src="http://placehold.it/350x150" />';
$str = preg_replace('/^'b(https?):'/'/[-A-Z0-9+&@#'/%?=~_|$!:,.;]*[A-Z0-9+&@#'/%=~_|$]/i', '', $str);
echo $str;

在线演示


或者简单地获得你需要的东西:

/(<img.*'/>)/i

在线演示

尝试:

<[^>]*(*SKIP)(*FAIL)|'b(https?):'/'/[-A-Z0-9+&@#'/%?=~_|$!:,.;]*[A-Z0-9+&@#'/%=~_|$]

<[^>]*捕获未闭合的<内的所有事物,而(*SKIP)(*FAIL)|跳过它们。

剩下的就是正则表达式。