使用substr_count计算正则表达式

时间:2015-10-12 07:27:28

标签: php

如何计算字符串上的所有特殊字符? 例如:

$sample_string = "!!~~Sample string";
echo substr($sample_string, special character);

所以输出为4。

4 个答案:

答案 0 :(得分:1)

By Regex

$sample_string = "!!~~Sample string";

preg_match_all("/\W/",$sample_string,$match);

echo count($match);

答案 1 :(得分:0)

substr_count()不适用于正则表达式,因此您必须对要删除的每个字符执行substr_count()

$str = preg_replace('/[^ a-z0-9]+/i', '', $sample_string);
$number_of_sprecial_chars = strlen($sample_string)-strlen($str);

删除字符串中的所有特殊字符,然后为您提供原始版本和修改版本之间的差异。

如果特殊字符仅在开头出现(或者您只想要替换那些字符),

echo preg_replace('/^[^ a-z0-9]+/', '', $sample_string);

将直接为您提供不带特殊字符的字符串(不使用substr())。

答案 2 :(得分:0)

$ pattern =' / [!@#$%^& *()] /' //将匹配[]

中任何符号的一次出现
int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG_PATTERN_ORDER [, int $offset = 0 ]]] )

对字符串执行全局正则表达式匹配。将所有匹配的主题搜索到模式中给出的正则表达式,并按照flags指定的顺序将它们放入匹配项中。

找到第一场比赛后,后续搜索将从最后一场比赛结束时继续。

答案 3 :(得分:0)

您可以简单地使用preg_replace_callback功能和closure一样使用

$sample_string = "!!~~Sample string";
$count = 0;
preg_replace_callback('/[^\h\w]/', function($m)use(&$count) {
    $count++;
}, $sample_string);
echo $count;//4

Demo