Php 使用preg_replace仅替换第一个匹配项

Php 使用preg_replace仅替换第一个匹配项,php,regex,string,Php,Regex,String,我正在测试phpList中的str_replace,我想替换字符串的第一个匹配项。我在其他帖子上发现,如果我想替换字符串的第一个匹配项,我应该使用preg_replace,问题是preg_replace由于某种原因没有返回字符串 两者 及 将空字符串写入文件。我想知道如何得到一个返回字符串,str_replace似乎不适用于第一个匹配。但是,str_replace将返回一个字符串。的执行正则表达式匹配和替换。您将传递一个字符串,而不是有效的正则表达式作为第一个参数 实际上,如果您只想执行常规的查

我正在测试phpList中的str_replace,我想替换字符串的第一个匹配项。我在其他帖子上发现,如果我想替换字符串的第一个匹配项,我应该使用preg_replace,问题是preg_replace由于某种原因没有返回字符串

两者

将空字符串写入文件。我想知道如何得到一个返回字符串,str_replace似乎不适用于第一个匹配。但是,str_replace将返回一个字符串。

的执行正则表达式匹配和替换。您将传递一个字符串,而不是有效的正则表达式作为第一个参数

实际上,如果您只想执行常规的查找和替换操作,preg_replace是错误的工具。您可以使用和执行单个替换,例如:

$find = basename($html_images[$i]);
$string_test = $this->Body;
if (($pos = strpos($string_test, $find)) !== false) {
    $string_test = substr_replace($string_test, "cid:$cid", $pos, strlen($find));
}
使用preg_replace,您将得到如下结果:

$string_test = preg_replace('~' . preg_quote(basename($html_images[$i], '~') . '~', "cid:$cid", $this->Body, 1);

为方便起见,您可以先将两个参数中的任意一个包装到名为str_replace_的函数中。

preg_replace接受正则表达式作为第一个参数。我将查看正则表达式中可能存在的重复项。我试过这个fwrite$fp,str_replacebasename$html_images[$I],cid:$cid,$this->Body,1;使用stru_replace,它似乎不起作用。
$find = basename($html_images[$i]);
$string_test = $this->Body;
if (($pos = strpos($string_test, $find)) !== false) {
    $string_test = substr_replace($string_test, "cid:$cid", $pos, strlen($find));
}
$string_test = preg_replace('~' . preg_quote(basename($html_images[$i], '~') . '~', "cid:$cid", $this->Body, 1);