【问题标题】:how to detect str_replace() has done replacement or not? and how many?如何检测 str_replace() 是否进行了替换?有多少?
【发布时间】:2015-09-06 08:35:53
【问题描述】:

我有两个字符串,如下所示:

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

现在我用str_replace();代替str1str2中的'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

现在我想echo:

  • '匹配已找到' for str1

  • str2'找不到匹配的'

而且我还想知道是否可以计算找到的匹配数量?例如对于str11

【问题讨论】:

    标签: php str-replace string-matching


    【解决方案1】:

    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;
    

    【讨论】:

    • PHP_EOLpre-defined constant 对应于 end of line"\n""\r\n" 取决于您的 PHP 是在 *nix 还是 Windows 平台上运行(不是每个人都在那里运行 PHP通过网络服务器发送,<br /> 在您从命令行执行代码时没有任何意义)
    • 你不能只为这两个函数中的每一个分配一个不同的变量吗?例如 $counter1 和 $counter2?
    • @Tarquin - 是的,我可以,但为什么呢?
    • 更多地询问其用户是否可控或设置。我从来不知道该函数中存在第四个选项。此外,您的措辞方式还不清楚您如何表示无法计算每个替换。感谢您的澄清。
    • 我指出的问题是,如果您执行$result = str_replace(['a','b'], ['c','d'], $string, $counter); 之类的操作,那么您无法分辨有多少个人a 被替换为c,以及有多少个人b 被替换为@ 987654334@,总共有多少人更换
    猜你喜欢
    • 2015-12-06
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 2014-09-11
    相关资源
    最近更新 更多