【问题标题】:Using preg_replace to replace only first match使用 preg_replace 仅替换第一个匹配项
【发布时间】:2014-03-17 05:13:00
【问题描述】:

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

两者

$fp = fopen('/var/www/data.txt', 'w');
$string_test = preg_replace(basename($html_images[$i]), "cid:$cid", $this->Body,1);
fwrite($fp,$string_test);
fclose($fp);

$fp = fopen('/var/www/data.txt', 'w');
fwrite($fp,preg_replace(basename($html_images[$i]), "cid:$cid", $this->Body,1));
fclose($fp);

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

【问题讨论】:

标签: php regex string


【解决方案1】:

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

相反,您可能正在寻找进行字符串替换的str_replace()

【讨论】:

  • 我会研究正则表达式。我试过这个 fwrite($fp,str_replace(basename($html_images[$i]), "cid:$cid", $this->Body,1));使用 str_replace,它似乎不起作用。
【解决方案2】:

实际上,如果您只想执行常规查找和替换操作,preg_replace() 是错误的工具。例如,您可以使用 strpos()substr_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_first() 的函数中。

【讨论】:

    猜你喜欢
    • 2011-10-07
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 2011-12-09
    • 2020-12-09
    • 2013-06-15
    • 1970-01-01
    • 2021-04-16
    相关资源
    最近更新 更多