Home > Article > Backend Development > How to verify if string is empty with PHP regular expression
In PHP, we can use regular expressions to verify whether a string is empty. Cases where the string is empty include the following:
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!