11

I have a string in php like this.

$str = "ABCCCDE" //Contains repeated character CCC more than 2 times

I want to know if there is any repeated characters more than 2 times using regular expression.

Thanks in advance

0

2 Answers 2

23
if (preg_match('/(.)\\1{2}/', $str))
   echo "Has 3 same characters consecutively!";

The (.) will match any character (except new lines), and the \1 will match a pattern same as the first matched group — in this case, the character we've just matched. So this RegEx will match 3 same consecutive characters.

Sign up to request clarification or add additional context in comments.

1 Comment

It returns 1 when there is string "abccde". It should return 1 only there is a repeated character more than 2 times
4

You can use:

'/(.)\1\1/'

E.g.:

preg_match('/(.)\1\1/', $str, $matches);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.