PHP检查字符串中字符的出现次数

时间:2011-03-08 10:16:36

标签: php regex

我得到了这样的字符串:

car-122-334
bike-123
boat

我想知道字符串中有多少“连字符”。如果有2个连字符返回2,如果0连字符返回0 ...

3 个答案:

答案 0 :(得分:5)

在PHP中使用substr_count方法。不需要正则表达式。

echo substr_count($text, '-');

http://www.php.net/manual/en/function.substr-count.php

答案 1 :(得分:4)

来自php.net:substr_count

int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )

例如:

$text = "car-122-334";
echo substr_count ($text, '-'); // --> 2

答案 2 :(得分:1)

请参阅http://www.php.net/manual/en/function.substr-count.phphttp://php.net/manual/fr/function.preg-match.php

substr_count将为您提供您期望的$count = substr_count($str, "-");