Check if String is Binary in PHP

This tutorial will discuss how to check if string is binary in PHP.

To check if a string contains only binary numbers, we need to verify that it contains only zeros and ones.

We can achieve this using a regular expression pattern i.e.

'/^[01]+$/'

By calling the preg_match() function in PHP and passing the regex pattern ‘/^[01]+$/’ as the first argument and the string as the second argument, we can determine if the string matches the given pattern. If the string contains a binary number, the function will return 1; otherwise, it will return 0.

We have created a separate function to check if a string contains a binary number,

function isValidBinaryString($binaryString)
{
    return preg_match('/^[01]+$/', $binaryString) === 1;
}

It accepts a string as an argument and returns true if the string contains a binary number.

Let’s see the complete example,

<?php
/**
 * Check if a string represents a valid binary number.
 *
 * @param string $binaryString The binary string to validate.
 * @return bool True if the string is a valid binary number, false otherwise.
 */
function isValidBinaryString($binaryString)
{
    return preg_match('/^[01]+$/', $binaryString) === 1;
}


$binaryString = '111101101';

// Check if string contains a valid binary number
if (isValidBinaryString($binaryString)) {
    echo "$binaryString is a valid binary string.";
} else {
    echo "$binaryString is not a valid binary string.";
}
?>

Output

111101101 is a valid binary string.

Summary

Today, we learned how to check if string is binary in PHP.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top