tags:

views:

104

answers:

4

I've wanted to check if a number in PHP was proper binary. So far I've added this to check if it is devisable by 8:

if(strlen($binary) % 8 == 0){
        return true;
} else {
        return false;
}

It works, but it obviously allows other numbers to be placed in, such as 22229999.

What method can I use to make sure only 1's and 0's are in the string? such as 10001001. Not sure how to go about this.

+2  A: 
if (preg_match('~^[01]+$~', $str))
{
    echo 'is binary';
}

Inspired by Techpriester's answer (fixed bug):

if (in_array(count_chars($str, 3), array('0', '1', '01'))
{
    echo 'is binary';
}
Alix Axel
+1  A: 
if ( preg_match('#^[01]+$#', $string) )
kemp
Malformed regex.
Alix Axel
Thanks, fixed (15 chars)
kemp
+2  A: 
for variety

if (!preg_match('/[^01]/', $str))
{
    echo 'is binary';
}
Paul Creasey
+4  A: 

This may be faster than firing up the regex engine:

if (strspn ( $subject , '01') == strlen($subject)) {
    echo 'It\'s binary!';
} else {
    echo 'Not binary!';
}

If you just look for simple characters or want to count them, regex is often quite slow while one or two built in string function can do the job much faster. Maybe this does apply here, maybe not.

After hearing some remarks in the comments, that this might not work, here's a test case:

<?php

$strings = array('10001001', '22229999', '40004000');

foreach ( $strings as $string )
{
    if ( strspn( $string, '01') == strlen( $string ) ) {
        echo $string . ' is binary!' . "\n";
    } else {
        echo $string . ' is NOT binary!' . "\n";
    }
}

It does the job.

Techpriester
@Tech, i doubt either has any significant performance impact anyway, so __much__ faster is not really likely. I'd imagine strspn is making use of a very regex like engine to do its work anyway.
Paul Creasey
@Techpriester: +1 from me, check my answer for an alternative solution.
Alix Axel
The performance gain of course depends on the amount of string that are matched. If he runs this over several thousand strings, it may be of impact.
Techpriester
This method does not seem to work. Allows 40004000 etc.
oni-kun
@paul: That's exactly the point, the php internal string functions mostly do not use regex. That's why it's alway worth trying simple text operations withour the preg functions.
Techpriester
@mememememe: I just tested it, and it works. I also tried your case ("40004000").
Techpriester
@Techpriester: Actually he's right, you have a bug. See http://www.ideone.com/DUsHFZeB.
Alix Axel
Doesn't make a lot of sense though... I'm totally confused now.
Alix Axel
@alix: Read your example code again, you forgot to change one "$subject" into "$string" (line 7). With correctly named variables, it works.
Techpriester
Ooops, you're right: http://www.ideone.com/1HCCtxVV
Alix Axel