Check if String is Blank in PHP

This tutorial will discuss multiple ways to check if string is blank in PHP.

Table Of Contents

Method 1: Using trim() function

To check if a string is blank, we need to make sure that it is either empty or contains only blank spaces.

For that, we can trim() the string and check if it is equal to an empty string. We have created a separate function,

function isBlankString($strValue)
{
    return trim($strValue) === '';
}

It accepts a string as an argument and returns true if the given string contains only whitespace characters.

Let’s see the complete example,

<?php
/**
 * Check if a string is blank (empty or contains only whitespace).
 *
 * @param string $strValue The string to validate.
 * @return bool True if the string is blank, false otherwise.
 */
function isBlankString($strValue)
{
    return trim($strValue) === '';
}

$strValue = '   ';

// Check if it is a blank string
if (isBlankString($strValue)) {
    echo "The string is blank.";
} else {
    echo "The string is not blank.";
}
?>

Output

The string is blank.

Method 2: Using regular expression

We can also use a regular expression to check if the string is blank. The regular expression pattern we are going to use is as follows:

'/^s*$/'

We will pass this regex pattern and the string as arguments to the preg_match() function of PHP. If it returns 1, then it means that the string contains only whitespace characters.

Let’s see the complete example,

<?php
/**
 * Check if a string is blank (empty or contains only whitespace).
 *
 * @param string $strValue The string to validate.
 * @return bool True if the string is blank, false otherwise.
 */
function isBlank($strValue)
{
    return preg_match('/^s*$/', $strValue) === 1;
}

$strValue = '         ';

// Check if it is a blank string
if (isBlank($strValue)) {
    echo "The string is blank.";
} else {
    echo "The string is not blank.";
}
?>

Output

The string is blank.

Summary

Today, we learned about multiple ways to check if string is blank 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