我有两个字符串,类似于这样:
$str1='this is the first text';
$str2='this is the second text';
现在我使用str_replace();
来替换str1
和str2
中"第一个"的单词。
对于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
:
str1
的"已找到匹配"未找到
str2
的"匹配"。
我还想知道,有可能统计找到的匹配数量吗?例如对于CCD_ 10是CCD_。
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;