John
John

Reputation: 13756

PHP detect variable length string contains any character other than 1

Using PHP I sometimes have strings that look like the following:

What is the most efficient way (preferably without regex) to determine if a string contains any character other then the character 1?

Upvotes: 1

Views: 351

Answers (3)

WBT
WBT

Reputation: 2495

Here's a one-line code solution that can be put into a conditional etc.:

strlen(str_replace('1','',$mystring))==0

It strips out the "1"s and sees if there's anything left.

User Don't Panic commented that str_replace could be replaced by trim:

strlen(trim($mystring, '1'))==0

which removes leading and trailing 1s and sees if there's anything left. This would work for the particular case in OP's request but the first option will also tell you how many non-"1" characters you have (if that information matters). Depending on implementation, trim might run slightly faster because PHP doesn't have to check any characters between the first and last non-"1" characters.


You could also use a string like a character array and iterate through from the beginning until you find a character which is not =='1' (in which case, return true) or reach the end of the array (in which case, return false).


Finally, though OP here said "preferably without regex," others open to regexes might use one:

 preg_match("/[^1]/", $mystring)==1

Upvotes: 6

Federkun
Federkun

Reputation: 36989

Another way to do it:

if (base_convert($string, 2, 2) === $string) {
    // $string has only 0 and 1 characters.
}

since your $string is basically a binary number, you can check it with base_convert.

How it works:

var_dump(base_convert('110', 2, 2)); // 110
var_dump(base_convert('11503', 2, 2)); // 110
var_dump(base_convert('9111111111111111111110009', 2, 2)); // 11111111111111111111000

If the returned value of base_convert is different from the input, there're something other characters, beside 0 and 1.

If you want checks if the string has only 1 characters:

if(array_sum(str_split($string)) === strlen($string)) {
    // $string has only 1 characters.
}

You retrieve all the single numbers with str_split, and sum them with array_sum. If the result isn't the same as the length of the string, then you've other number in the string beside 1.

Upvotes: 2

u_mulder
u_mulder

Reputation: 54796

Another option is treat string like array of symbols and check for something that is not 1. If it is - break for loop:

for ($i = 0; $i < strlen($mystring); $i++) {
   if ($mystring[$i] != '1') {
       echo 'FOUND!';
       break;
   }
}

Upvotes: 0

Related Questions