I’m trying to check if a string has a certain number of occurrence of a character.
Example:
$string = '123~456~789~000';
I want to verify if this string has exactly 3 instances of the character ~.
Is that possible using regular expressions?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As single character is technically a substring, and the task is to count the number of its occurences, I suppose the most efficient approach lies in using a special PHP function – substr_count:
Obviously, this approach won’t work if you need to count the number of pattern matches (for example, while you can count the number of ‘0’ in your string with
substr_count, you better usepreg_match_allto count digits).Yet for this specific question it should be faster overall, as
substr_countis optimized for one specific goal – count substrings – whenpreg_match_allis more on the universal side. )