Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/241.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何检测str_replace()是否进行了替换?有多少?_Php_Str Replace_String Matching - Fatal编程技术网

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

Php 如何检测str_replace()是否进行了替换?有多少?,php,str-replace,string-matching,Php,Str Replace,String Matching,我有两个字符串,类似这样: $str1='this is the first text'; $str2='this is the second text'; 现在我用str_替换;替换str1和str2中的“first”一词 对于str1:将找到主题,然后替换 str_replace('first','matched',$str1); // output: this is the matched text 对于str2:将找不到主题,str2不会更改 str_replace('first',

我有两个字符串,类似这样:

$str1='this is the first text';
$str2='this is the second text';
现在我用str_替换;替换str1和str2中的“first”一词

对于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
现在我想回应:

str1的“已找到匹配项”

str2的“未找到匹配项”

我还想知道,有没有可能数一数找到的匹配项的数量?e、 g.对于str1是1。

有第四个count参数,用于计算实际替换字符串的总数

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

编辑

第四个count参数用于计算实际替换字符串的总数

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

编辑


PHP_EOL是一个用于行尾的函数,可以是\n,也可以是\r\n,这取决于您的PHP是在*nix还是Windows平台上运行。并非所有人都在那里运行PHP以通过web服务器发送,当您从命令行执行代码时,这并不意味着什么。您是否可以为这两个函数中的每一个分配不同的变量$例如counter1和$counter2?@Tarquin-是的,我可以,但为什么?更多的是询问它的用户是否可以控制或设置。我从来不知道在这个功能中有第四个选项。此外,您的措辞也有点不清楚,您如何陈述无法计算每个替换项。感谢您的澄清。我指出的问题是,如果您执行类似$result=str_replace['a','b'],['c','d'],$string,$counter;那么你就无法知道有多少个a被c替换,有多少个b被d替换,只知道有多少个替换,P_EOL是a作为一个终端,或者\n或者\r\n取决于你的PHP是在a*nix还是Windows平台上运行,不是每个人都运行PHP通过web服务器发送,当您从命令行执行代码时,这并不意味着什么,您是否可以为这两个函数中的每一个都分配一个不同的变量$例如counter1和$counter2?@Tarquin-是的,我可以,但为什么?更多的是询问它的用户是否可以控制或设置。我从来不知道在这个功能中有第四个选项。此外,您的措辞也有点不清楚,您如何陈述无法计算每个替换项。感谢您的澄清。我指出的问题是,如果您执行类似$result=str_replace['a','b'],['c','d'],$string,$counter;那么你就不知道有多少个a被替换为c,有多少个b被替换为d,只知道总共有多少个替换
$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;