我有这样的字符串:
car-122-334
bike-123
boat
我想知道字符串中有多少个连字符。如果有2个连字符则返回2,如果没有连字符则返回0...
From 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
substr_count
方法,无需使用正则表达式。echo substr_count($text, '-');
请参考http://www.php.net/manual/en/function.substr-count.php和http://php.net/manual/fr/function.preg-match.php。
使用substr_count函数可以得到您期望的结果:$count = substr_count($str, "-");