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 oth开发者_运维技巧er 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.
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.
for variety
if (!preg_match('/[^01]/', $str))
{
echo 'is binary';
}
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';
}
if ( preg_match('#^[01]+$#', $string) )
精彩评论