尝试仅替换第一次出现的字符串会产生错误

Trying to replace only the first occurrence of a string produces an error

PHP7

代码:

$slug = '1196';
$id = '1';
str_replace($id, '', $slug, 1);

我的 objective 是要替换“1”的第一个实例,但我收到以下错误消息:

Fatal error: Only variables can be passed by reference

PHP 手册说:

str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) : mixed

我做错了什么?

第四个参数是一个变量,用于保存替换次数。这不是您想要发生的替换次数的限制。

If passed, this will be set to the number of replacements performed.

https://www.php.net/manual/en/function.preg-replace.php 有一个 limit 参数。例如

$slug = '1196';
$id = '1';
echo preg_replace('/' . $id . '/', '', $slug, 1);

https://3v4l.org/VrTcg