Check if a given String is Binary String or Not using PHP
Last Updated :
19 Mar, 2024
Given a String, the task is to check whether the given string is a binary string or not in PHP. A binary string is a string that should only contain the ‘0’ and ‘1’ characters.
Examples:
Input: str = "10111001"
Output: The string is binary.
Input: str = "123456"
Output: The string is not binary.
Using Regular Expression
One of the most efficient method to check if a string is a binary string is by using regular expressions. In this example, the isBinStr() function uses the preg_match() function to check if the input string matches the regular expression /^[01]+$/. This regular expression ensures that the string consists only of 0 and 1 characters. The function returns true if the string is binary and false otherwise.
Example: This example shows the usage of the above-mentioned approach.
PHP
<?php
function isBinStr($str) {
return preg_match('/^[01]+$/', $str) === 1;
}
$str1 = "101010";
$str2 = "123456";
echo isBinStr($str1)
? "The string is binary."
: "The string is not binary.";
echo "\n";
echo isBinStr($str2)
? "The string is binary."
: "The string is not binary.";
?>
OutputThe string is binary.
The string is not binary.
Using strspn( ) Function
The strspn() function returns the length of the initial segment of a string that contains only characters specified in the given string. In this example, the isBinStr() function uses the strspn() function to determine the length of the initial segment of the string that contains only 0 and 1. If this length is equal to the total length of the string (strlen($string)), the string is binary.
Example: This example shows the usage of the above-mentioned approach.
PHP
<?php
function isBinStr($str) {
return strspn($str, '01') === strlen($str);
}
$str1 = "101010";
$str2 = "123456";
echo isBinStr($str1)
? "The string is binary."
: "The string is not binary.";
echo "\n";
echo isBinStr($str2)
? "The string is binary."
: "The string is not binary.";
?>
OutputThe string is binary.
The string is not binary.
Manual Iteration
While less efficient, in this example, the isBinStr() function iterates through each character of the input string and checks if it is either 0 or 1. If any character is not 0 or 1, the function returns false. Otherwise, it returns true.
Example: This example shows the usage of the above-mentioned approach.
PHP
<?php
function isBinStr($str) {
for ($i = 0; $i < strlen($str); $i++) {
if ($str[$i] !== '0' && $str[$i] !== '1') {
return false;
}
}
return true;
}
$str1 = "101010";
$str2 = "123456";
echo isBinStr($str1)
? "The string is binary."
: "The string is not binary.";
echo "\n";
echo isBinStr($str2)
? "The string is binary."
: "The string is not binary.";
?>
OutputThe string is binary.
The string is not binary.
Share your thoughts in the comments
Please Login to comment...