3

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.

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

8 Comments

@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.
@Techpriester: +1 from me, check my answer for an alternative solution.
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.
@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.
@alix: Read your example code again, you forgot to change one "$subject" into "$string" (line 7). With correctly named variables, it works.
|
2
for variety

if (!preg_match('/[^01]/', $str))
{
    echo 'is binary';
}

Comments

2
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';
}

Comments

1
if ( preg_match('#^[01]+$#', $string) )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.