如何检测 str_replace() 是否进行了替换?有多少?

how to detect str_replace() has done replacement or not? and how many?

我有两个字符串,像这样:

$str1='this is the first text';
$str2='this is the second text';

现在我用str_replace();来代替str1str2中的'first'。[=25] =]

对于str1:主题会被找到然后被替换

str_replace('first','matched',$str1);
// output: this is the matched text

对于str2:主题将找不到并且str2不会改变。

str_replace('first','matched',$str2);
// output: this is the second text

现在我想echo:

另外我想知道是否可以计算找到的匹配数量?例如str11.

str_replace() 的第四个 count 参数计算实际对字符串进行的替换总数

如果您要进行多次替换(使用数组),它不会告诉您每次替换的数量,但它会告诉您总计数

编辑

$str1 = 'this is the first text';
$result1 = str_replace('first','matched',$str1, $counter);
echo $counter, ' replacements were made', PHP_EOL;

$result2 = str_replace('is','**',$str1, $counter);
echo $counter, ' replacements were made', PHP_EOL;