Home >Backend Development >PHP Tutorial >How to verify if string is empty with PHP regular expression

How to verify if string is empty with PHP regular expression

PHPz
PHPzOriginal
2023-06-24 08:46:372271browse

In PHP, we can use regular expressions to verify whether a string is empty. Cases where the string is empty include the following:

  1. The string contains only spaces.
  2. The string length is 0.
  3. The string is null or undefined.

Next, we will introduce how to use regular expressions in PHP to verify these situations.

Regular expression: s

This regular expression can be used to match strings containing only spaces. Where s means matching spaces, means matching one or more.

Code example:

function isEmptyString($string) {
    if (preg_match('/s+/', $string)) {
        return true;
    }
    return false;
}

Regular expression: ^$

This regular expression can be used to match the case where the string length is 0. Among them, ^ means matching the beginning of the string, and $ means matching the end of the string.

Code example:

function isEmptyString($string) {
    if (preg_match('/^$/', $string)) {
        return true;
    }
    return false;
}

Regular expression:/^s*$/

This regular expression can be used to match strings that only contain spaces, and also Can match the case where the string length is 0. Where s means matching spaces, * means matching zero or more.

Code example:

function isEmptyString($string) {
    if (preg_match('/^s*$/', $string)) {
        return true;
    }
    return false;
}

Determine whether the string is null or undefined

We can use the is_null() function in PHP to determine whether the string is null, use The isset() function in PHP determines whether a string is undefined.

Code example:

function isEmptyString($string) {
    if (is_null($string) || !isset($string)) {
        return true;
    }
    return false;
}

Finally, we can encapsulate these methods in a class to make the code clearer and more readable.

class Validator {
    public static function isEmptyString($string) {
        if (is_null($string) || !isset($string)) {
            return true;
        }
        if (preg_match('/^s*$/', $string)) {
            return true;
        }
        return false;
    }
}

Usage:

if (Validator::isEmptyString($string)) {
    echo '字符串为空';
} else {
    echo '字符串不为空';
}

The above is the detailed content of How to verify if string is empty with PHP regular expression. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn