Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php Regular Expression repeated characters

Tags:

regex

php

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

like image 376
Novice Avatar asked Sep 25 '10 07:09

Novice


People also ask

How do you repeat a regular expression?

An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once. An expression followed by '? ' may be repeated zero or one times only.

What is dot plus in regex?

The next token is the dot, which matches any character except newlines. The dot is repeated by the plus. The plus is greedy. Therefore, the engine will repeat the dot as many times as it can. The dot matches E, so the regex continues to try to match the dot with the next character.

What does star mean in regex?

The asterisk is known as a repeater symbol, meaning the preceding character can be found 0 or more times. For example, the regular expression ca*t will match the strings ct, cat, caat, caaat, etc.

Has been considered the benchmark for powerful regular expression?

Perl has long been considered the benchmark for powerful regular expressions. PHP uses a C library called pcre to provide almost complete support for Perl's arsenal of regular expression features.


2 Answers

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.

like image 111
kennytm Avatar answered Sep 24 '22 03:09

kennytm


You can use:

'/(.)\1\1/'

E.g.:

preg_match('/(.)\1\1/', $str, $matches);
like image 41
Matthew Flaschen Avatar answered Sep 24 '22 03:09

Matthew Flaschen