PHP - check if string contains the same character

I want to check if a string contains the same characters, for example, if my string is equal to 'aaaaaa' or 'bbbb' or '*****' , it should return true or if it contains 'aaab' or '**%***' it should return false , how to do it in PHP?

PS: Is there a way to do this without RegEx?

+5
source share
7 answers

You can split per character, and then count array for unique values.

 if(count(array_count_values(str_split('abaaaa'))) == 1) { echo 'True'; } else { echo 'false'; } 

Demo: https://eval.in/760293

+6
source
 count(array_unique(explode('', string)) == 1) ? true : false; 
+5
source

You can use regex with backlink:

 if (preg_match('/^(.)\1*$/', $string)) { echo "Same characters"; } 

Or a simple loop:

 $same = true; $firstchar = $string[0]; for ($i = 1; $i < strlen($string); $i++) { if ($string[$i] != $firstchar) { $same = false; break; } } 
+3
source

Hope this works.

Regex: ^(.)\1{1,}

^ : start of line

(.) : match and record a single character.

\1{1,} : use the captured character one or more times.

For this you can use regex

OR

PHP demo

 $string="bbbb"; if($length=strlen($string)) { substr_count($string,$string[0]); if($length==substr_count($string,$string[0])) { echo "Do something"; } } 
+1
source
 strlen(str_replace($string[0], '', $string)) ? false : true; 
+1
source

For pleasure:

 <?php function str2Dec($string) { $hexstr = unpack('H*', $string); $hex = array_shift($hexstr); return hexdec($hex); } function isBoring($string) { return str2Dec($string) % str2Dec(substr($string, 0, 1)) === 0; } $string1 = 'tttttt'; $string2 = 'ttattt'; var_dump(isBoring($string1)); // => true var_dump(isBoring($string2)); // => false 

Obviously, this only works in small lines, because when it gets big enough, INT will overflow, and the mod will not give the correct value. So, do not use this :) - send it simply to show another idea from the usual ones.

+1
source

To my great surprise, all the other answers are too zealous. Some of them convert a string to an array, replacing characters using regular expression, looping, and writing custom functions.

That is all there is to doing, two string functions:

 $string='aaaba'; var_export(strlen(count_chars($string,3))>1?false:true); // false 

These two functions ( count_chars() and strlen() ) were designed specifically for this purpose.

+1
source

Source: https://habr.com/ru/post/1265851/


All Articles