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
<?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

Similar Reads

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....

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....

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....