php 正则表达式匹配空(或所有空白)字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1833999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
regular expression to match an empty (or all whitespace) string
提问by Tony Stark
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 help!
我想匹配一个可以有任何类型的空白字符的字符串(特别是我使用的是 PHP)。或者任何判断字符串是否为空或只有空格的方法也会有所帮助!
回答by Jan Han?i?
You don't need regular expressions for that, just use:
您不需要正则表达式,只需使用:
if ( Trim ( $str ) === '' ) echo 'empty string';
回答by nickf
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
}
回答by Jared
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!)
编辑:更新正则表达式以匹配真正的空字符串 - 每个 nickf(谢谢!)
回答by Emre Yazici
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.
^[\s]* 表示文本必须以零个或多个空格开头,[\s]*$ 表示必须以零个或多个空格结尾,因为表达式是“零个或多个”,它也匹配空字符串。
回答by Rob
You don't really need a regex
你真的不需要正则表达式
if($str == '') { /* empty string */ }
elseif(trim($str) == '') { /* string of whitespace */ }
else { /* string of non-whitespace */ }
回答by lsblsb
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"
回答by yu_sha
Expression is \A\s*+\Z
表达式是 \A\s*+\Z

