php 如果字符串只包含空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2352779/
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
If string only contains spaces?
提问by tarnfeld
How can i check to see if a string onlycontains spaces?
如何检查字符串是否仅包含空格?
回答by John Knoeller
if (strlen(trim($str)) == 0)
or if you don't want to include empty strings,
或者如果您不想包含空字符串,
if (strlen($str) > 0 && strlen(trim($str)) == 0)
回答by David Murdoch
from: https://stackoverflow.com/a/2992388/160173
来自:https: //stackoverflow.com/a/2992388/160173
If you want to upvote, do it on the other answer, not this one!
如果您想投票,请在另一个答案上进行投票,而不是这个!
This will be the fastest way:
这将是最快的方式:
$str = ' ';
if (ctype_space($str)) {
}
Returns falseon empty string because empty is not white-space. If you need to include an empty string, you can add || $str == ''This will still result in faster execution than regex or trim.
返回false空字符串,因为空不是空白。如果您需要包含一个空字符串,您可以添加|| $str == ''这仍然会导致比 regex 或 trim 更快的执行。
as a function:
作为一个函数:
function stringIsNullOrWhitespace($text){
return ctype_space($text) || $text === "" || $text === null;
}
回答by Enrico Carlesso
echo preg_match('/^ *$/', $string)
Should work.
应该管用。
回答by Mark Byers
Use a regular expression:
使用正则表达式:
$result = preg_match('/^ *$/', $text);
If you want to test for any whitespace, not just spaces:
如果您想测试任何空格,而不仅仅是空格:
$result = preg_match('/^\s*$/', $text);
回答by mpen
I think using regexes is overkill, but here's another sol'n anyway:
我认为使用正则表达式是矫枉过正,但无论如何这是另一个解决方案:
preg_match('`^\s*$`', $str)
回答by migajek
check if result of trim() is longer than 0
检查 trim() 的结果是否长于 0
回答by ghostdog74
another way
其它的办法
preg_match("/^[[:blank:]]+$/",$str,$match);
回答by Emanuil Rusev
chop($str) === ''
This should be enough.
这应该足够了。
回答by Azam Alvi
If you are using Ck-editor then you should do this
如果您使用的是 Ck-editor,那么您应该这样做
if( strlen(trim($value,' ')) == 0 ){
echo "White space found!"
}
回答by Felipe Buccioni
Another way, just for play
另一种方式,只是为了玩
<?php
function is_space_str($str) {
for($i=0,$c=strlen($str);$i<$c;$i++) {
switch (ord($str{$i})) {
case 21:
case 9:
case 10:
case 13:
case 0:
case 11:
case 32:
break;
default:
return false;
}
}
return true;
}

