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

前端 未结 7 1145
孤城傲影
孤城傲影 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:57

    Checking the length of the trimmed string, or comparing the trimmed string to an empty string is probably the fastest and easiest to read, but there are some cases where you can't use that (for example, when using a framework for validation which only takes a regex).

    Since no one else has actually posted a working regex yet...

    if (preg_match('/\S/', $text)) {
        // string has non-whitespace
    }
    

    or

    if (preg_match('/^\s*$/', $text)) {
        // string is empty or has only whitespace
    }
    

提交回复
热议问题