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

ang*_*iwi 2 php regex

我有这样的字符串:

car-122-334
bike-123
boat
Run Code Online (Sandbox Code Playgroud)

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

slh*_*hck 7

来自php.net:substr_count

int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
Run Code Online (Sandbox Code Playgroud)

例如:

$text = "car-122-334";
echo substr_count ($text, '-'); // --> 2
Run Code Online (Sandbox Code Playgroud)


Joh*_*hnP 5

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

echo substr_count($text, '-');
Run Code Online (Sandbox Code Playgroud)

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