php 检查字符串是否只是空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2992329/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:21:04  来源:igfitidea点击:

Check if string is just white space?

php

提问by JD Isaacks

Possible Duplicate:
If string only contains spaces?

可能的重复:
如果字符串只包含空格?

I do not want to change a string nor do I want to check if it containswhite space. I want to check if the entire string is ONLYwhite space. What the best way to do that?

我不想更改字符串,也不想检查它是否包含空格。我想检查整个字符串是否只有空格。最好的方法是什么?

回答by webbiedave

This will be the fastest way:

这将是最快的方式:

$str = '      ';
if (ctype_space($str)) {

}

Returns false on empty string because empty is notwhite-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,因为 empty不是空格。如果您需要包含一个空字符串,您可以添加|| $str == ''这仍然会导致比 regex 或 trim 更快的执行。

ctype_space

ctype_space

回答by MANCHUCK

since trim returns a string with whitespace removed, use that to check

由于 trim 返回一个删除了空格的字符串,请使用它来检查

if (trim($str) == '')
{
 //string is only whitespace
}

回答by svens

if( trim($str) == "" )
    // the string is only whitespace

This should do the trick.

这应该可以解决问题。

回答by Wrikken

preg_match('/^\s*$/',$string)

preg_match('/^\s*$/',$string)

change * to + if empty is not allowed

如果不允许为空,则将 * 更改为 +