regular expression to match an empty (or all whitespace) string

前端 未结 7 1146
孤城傲影
孤城傲影 2021-01-12 10:04

i want to match a string that can have any type of whitespace chars (specifically I am using PHP). or any way to tell if a string is empty or just has whitespace will also h

相关标签:
7条回答
  • 2021-01-12 10:39

    You don't need regular expressions for that, just use:

    if ( Trim ( $str ) === '' ) echo 'empty string';
    
    0 讨论(0)
  • 2021-01-12 10:43
    if(preg_match('^[\s]*[\s]*$', $text)) {
        echo 'Empty or full of whitespaces';
    }
    

    ^[\s]* means the text must start with zero or more whitespace and [\s]*$ means must end with zero or more whitespace, since the expressions are "zero or more", it also matches null strings.

    0 讨论(0)
  • 2021-01-12 10:43

    Expression is \A\s*+\Z

    0 讨论(0)
  • 2021-01-12 10:45
    if (preg_match('^[\s]*$', $text)) {
        //empty
    } 
    else {
        //has stuff
    }
    

    but you can also do

    if ( trim($text) === '' ) {
        //empty
    }
    

    Edit: updated regex to match a truly empty string - per nickf (thanks!)

    0 讨论(0)
  • 2021-01-12 10:49

    You don't really need a regex

    if($str == '') { /* empty string */ }
    elseif(trim($str) == '') { /* string of whitespace */ }
    else { /* string of non-whitespace */ }
    
    0 讨论(0)
  • 2021-01-12 10:49

    The following regex checks via lookahead and lookbehind assertion, if the string contains whitespace at the beginning or at the end or if the string is empty or contains only whitespace:

    /^(?!\s).+(?<!\s)$/i
    

    invalid (inside "):

    ""
    " "
    " test"
    "test "
    

    valid (inside "):

    "t"
    "test"
    "test1 test2"
    
    0 讨论(0)
提交回复
热议问题