且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式匹配特定字符的确切出现次数

更新时间:2023-02-20 22:22:47

由于单个字符在技术上是一个子字符串,任务是计算它出现的次数,我认为最有效的方法是使用特殊的 PHP 函数- substr_count:

As single character is technically a substring, and the task is to count the number of its occurences, I suppose the most efficient approach lies in using a special PHP function - substr_count:

$string = '123~456~789~000';
if (substr_count($string, '~') === 3) {
  // string is valid
}

显然,如果您需要计算模式匹配的数量,这种方法将不起作用(例如,虽然您可以使用 substr_count 计算字符串中0"的数量,但您***使用 preg_match_all 计算数字).

Obviously, this approach won't work if you need to count the number of pattern matches (for example, while you can count the number of '0' in your string with substr_count, you better use preg_match_all to count digits).

然而,对于这个特定问题,它总体上应该更快,因为 substr_count 针对一个特定目标进行了优化 - 计算子字符串 - 当 preg_match_all 更适用于通用方面时.)

Yet for this specific question it should be faster overall, as substr_count is optimized for one specific goal - count substrings - when preg_match_all is more on the universal side. )