简体   繁体   English

PHP为什么在str_replace中的第四个参数不起作用?

[英]PHP why is my fourth parameter in str_replace not working?

I'm a beginner in PHP and I can't understand why this does not work. 我是PHP的初学者,不明白为什么这行不通。

<?php
$count = 1;
$body = 'Biceps, Triceps, Quadriceps, Chest, Calves, Forearms are great to train!';
$body = str_replace('Chest', 'Quadriceps', $body);
$body = str_replace('Calves', 'Triceps', $body);
$body = str_replace('Forearms', 'Biceps', $body);
$body = str_replace('Biceps', 'Forearms', $body, $count);
$body = str_replace('Triceps', 'Calves', $body, $count);
$body = str_replace('Quadriceps', 'Chest', $body, $count);
echo $body;
?>

For the latter three replacements, although the fourth parameter, which supposedly defines the number of replacements is set to 1, they still perform the replacement twice and I end up with this output: 对于后三个替换,尽管第四个参数(假设它定义了替换的数量)设置为1,但它们仍然执行两次替换,最终得到以下输出:

'Forearms, Calves, Chest, Chest, Calves, Forearms are great to train!' “前臂,小腿,胸部,胸部,小腿,前臂非常适合训练!”

instead of: 代替:

'Forearms, Calves, Chest, Quadriceps, Triceps, Biceps are great to train!' “前臂,小腿,胸部,四头肌,三头肌,二头肌非常适合训练!”

...why?! ...为什么?!

What the manual say is: 手册说的是:

If passed, this will be set to the number of replacements performed. 如果通过,它将设置为执行的替换次数。

Additionally, the function signature features the & symbol to indicate that the function writes into the variable you pass to it: 此外,函数签名带有&符号,以指示该函数写入传递给它的变量中:

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

In short, it's a report, not a setting. 简而言之,它是报告,而不是设置。

Each replace happens before the next is performed. 每次替换都在执行下一个替换之前发生。

  • In the third replacement, you're changing "Forearms" to "Biceps." 在第三个替换中,您将“前臂”更改为“二头肌”。
  • In the fourth replacement, you're changing it back when you change 在第四个替换项中,您将在更改时将其更改回
    "Biceps" to "Forearms." 从“二头肌”到“前臂”。

Similar problem with 2nd and 4th replacements. 第2次和第4次替换的类似问题。 The "1" you're passing in to str_replace doesn't do anything. 您传递给str_replace的“ 1”没有任何作用。

Consider using preg_replace if you only want the first instance to be replaced. 如果只希望替换第一个实例,请考虑使用preg_replace

The fourth parameter (from the manual )... 第四个参数(来自手册 )...

count 计数

If passed, this will be set to the number of replacements performed. 如果通过,它将设置为执行的替换次数。

So not the amount to do, but the amount done. 所以不是要做的事,而是要做的事。

Just as an alternative, try... 作为替代方案,尝试...

$body1 = strtr($body, 
    ['Chest'=>'Quadriceps','Calves' => 'Triceps', 
        'Forearms' => 'Biceps', 'Biceps' => 'Forearms',
        'Triceps' => 'Calves', 'Quadriceps' => 'Chest'
    ] );

Which outputs 哪个输出

Forearms, Calves, Chest, Quadriceps, Triceps, Biceps are great to train!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM