简体   繁体   中英

PHP check occurences of a character inside a string

I got strings like these:

car-122-334
bike-123
boat

I want to know how many "hyphens" in the string. if there is 2 hyphens return 2, if 0 hyphen return 0...

use the substr_count method in PHP. No need for regex.

echo substr_count($text, '-');

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

From php.net: substr_count

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

For example:

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

See http://www.php.net/manual/en/function.substr-count.php and http://php.net/manual/fr/function.preg-match.php .

substr_count will give you what you expect $count = substr_count($str, "-");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM