使用 PHP 有条件地删除文本中的子字符串


Conditionally remove substrings in text with PHP

我的场景是我有一个包含原始html的字符串,例如:

Remove this tag: <img src="path/to/image">. 
Also remove this tag: <img src="path/to/second/image">. 
But don't touch this <img src="cid:1259asdhasi">.

我需要做的是在我的字符串中找到所有 img 标签,检查它们的src是否以 cid: 开头,如果没有,请删除整个标签。

有什么想法吗?

preg_replace中使用基于前瞻的负正则表达式

preg_replace('~<img'b[^>]*'ssrc="(?!cid:)[^>]*>~', '', $str);

演示