How to use strspn( ) Function In PHP
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
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.";
?>
Output
The string is binary. The string is not binary.
Check if a given String is Binary String or Not using PHP
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.
Table of Content
- Using Regular Expression
- Using strspn( ) Function
- Manual Iteration