如何删除 UTF-8 字符串中带有 SRC 值的整个 img 元素?

how to remove whole img element with a SRC value in an UTF-8 string?

例如这是一个算法:

$text = 'some text1 <img src="1.jpg" />  some text2 <img src="2.jpg">';
if($src == '1.jpg')
   remove(img tag in $text)
echo htmlspecialchars($text, ENT_QUOTES, "UTF-8")

结果必须是:

some text1 some text2 <img src="2.jpg>"

使用str_replace()函数删除所有1.jpg张图片。

$text = 'some text1 <img src="1.jpg" />  some text2 <img src="2.jpg">';
$text2 = str_replace('<img src="1.jpg" />','',$text);
echo $text2; // Will output "some text1   some text2 "

如果您想 运行 这几个 src 值,例如在循环中,将第 2 行更改为:

$filename = 'xyz.jpg'; //set this to current filename that you want to remove from the string
$text2 = str_replace('<img src="' . $filename . '" />','',$text);

详情见PHP manual: str_replace

直接使用preg_replace,无条件,需要preg_match

$text = 'some text1 <img src="1.jpg" />  some text2 <img src="2.jpg">';

echo preg_replace('~(<img.*[\'"]1\.jpg[\'"].*>)~', '', $text); // some text1 some text2 <img src="2.jpg">

需要第一个 ['"] 以避免删除例如。 a1.jpg 文件,第二个是可选的。最好了解它是如何工作的。

更新
由于下面的评论,这里是带有变量名称的更新版本:

$file = '1.jpg';
$text = 'some text1 <img src="1.jpg" />  some text2 <img src="2.jpg" />';
echo preg_replace('~<img[^>]+[\'"]' . $file . '[\'"].*?/>~', '', $text);