Match a string that contains any 5 equivalent digits

Hi, I want to check if a string contains 5 equivalent digits. Examples of matches:

ABC33Z333
222SD22DD
99999ABCX

and so on.

What’s the best way to do so? Thanks

Loop through every character in the string, using an associative array to keep count of how many times you see a character. Once you’ve counted five the same, you have a match. If you get to the end of the string without seeing five of the same, you don’t have a match.

But this will be slow, especially since I have a long array of strings. Is there a way to do it using regex?

I don’t think so. And even if there was it would have to do the same amount of work as a manual loop; there’s no getting around the requirement of looking at the entire string.

A. You didn’t state what you want to do if there is or is not a match.
B. There’s a function to get a count of characters in a string - count_chars()
C. You can then use in_array() to test if there’s exactly 5 of any character in a result.
D. You can also use array_filter() if you only want to keep the values that satisfy the test.

$arr =[
'ABC33Z333',
'222SD22DD',
'99999ABCX',
'121345678'
];

// array_filter call-back function
function _keep_5($element)
{
	return in_array(5,count_chars($element,1));
}

$result = array_filter($arr,'_keep_5');

print_r($result);

Thank you, what if I have a single string only not an array.

Sponsor our Newsletter | Privacy Policy | Terms of Service