我想从字符串中删除所有 Base64 图像
<img src="data:image/png;base64,iVBORw0..="><img src="data:image/png;base64,iVBORw1..=">...
并将它们替换为 image1、image2 等。
<img src=" image1"><img src=" image2">...
因此,我删除了字符串的 base64 部分,并将其替换为“image”,后跟出现计数器,但它不起作用,所以我一直得到 image1。
我能做什么? 谢谢!!
这是我到目前为止的代码:
$replacement = "image";
$stringResult= deleteBase64_andReplace("data:", "=", $replacement, $string);
echo $stringResult;
function deleteBase64_andReplace($start, $end, $replacement, $string) {
$count = 0;
$pattern = '|' . preg_quote($start) . '(.*)' . preg_quote($end) . '|U';
while (strpos($string, $start) !== false) {
return preg_replace($pattern, $replacement.++$count, $string);
}
}
最佳答案
您需要替换 deleteBase64_andReplace
函数与
function deleteBase64_andReplace($start, $end, $replacement, $string) {
$count = 0;
$pattern = '|' . preg_quote($start, '|') . '(.*?)' . preg_quote($end, '|') . '|s';
while (strpos($string, $start) !== false) {
return preg_replace_callback($pattern, function($m) use ($replacement, &$count) {
return $replacement . ++$count;}, $string);
}
}
请参阅PHP demo 。输出为<img src="image1"><img src="image2">
.
注释:
-
preg_replace
替换为preg_replace_callback
能够对$count
进行更改替换后续匹配时 -
preg_quote($start, '|') . '(.*?)' . preg_quote($end, '|')
现在转义正则表达式分隔符字符,您选择了|
它也需要转义 - 我建议省略
U
标记并替换.*
与.*?
使正则表达式更加透明
关于php - 删除字符串之间的字符串并替换为文本加计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72257974/