I want to check if a string contains a character repeated zero or more times, for example:
If my string is aaaaaa
, bbbb
, c
or *****
it must return true
.
If it contains aaab
, cd
, or **%***
it must return false
.
In other words, if the string has 2 or more unique characters, it must return false
.
How to go about this in PHP?
PS: Is there a way to do it without RegEx?
The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .
The equals() method compare two strings on the basis of their values or content for equality. This method compare the strings ignoring the case( case-insensitive ). It returns true if values of both the strings is same ignoring the case, else return false.
Start with the first character, loop through the rest of the string to see if it matches. if there is no match, then repeat for the next character.
To check if a string contains special characters, call the test () method on a regular expression that matches any special character. The test method will return true if the string contains at least 1 special character and false otherwise. Copied! If you consider space to be a special character, add it between the square brackets []. Copied!
To find whether string has all the same characters. Traverse the whole string from index 1 and check whether that character matches with first character of string or not. If yes, than match until string size. If no, than break the loop.
A string consists of multiple characters and these characters can be letters, numbers, or special characters. For a beginner, it can be a bit tricky to find if it contains all characters of another string. There are numerous ways to check if a string contains all characters of another string.
Given a string, check if all the characters of the string are the same or not. Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
You could split
on every character then count
the array for unique values.
if(count(array_count_values(str_split('abaaaa'))) == 1) {
echo 'True';
} else {
echo 'false';
}
Demo: https://eval.in/760293
count(array_unique(explode('', string)) == 1) ? true : false;
You can use a regular expression with a back-reference:
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With