PHP怎么判断字符串是不是全是空格?

PHP与SEO 思享 911浏览

对于程序实现的某些功能,有时候会出现全部输入空格的情况,这种情况会导致程序报错。因此,在PHP中可以对这种情况进行提前判断反馈提示。那么如何实现呢?

ctype_space()函数

ctype_space()函数是PHP中的字符类型(CType)函数,用于检查给定的字符串是否包含空格。这里说的空格包含其他一些内容,例如“制表符”(水平,垂直),“换行符”,“回车”和“换页符”。

示例

$str = "        ";
if(ctype_space($str)) {
	echo "全部是空格啊";
} else {
	echo "不全是";

其他方法

另外,网上找了一下,也有其他方法,大概意思是对空格进行替换,最后判断长度是否等于0

mb_language('uni');
mb_internal_encoding('UTF-8');
$s = '     ';
if (strlen(preg_replace('/\s+/u','',$s)) == 0) {
	echo "String is empty.\n";
}

或者

$s = '  '; 
if (strlen(trim(preg_replace('/\xc2\xa0/',' ',$s))) == 0) { 
    echo "String is empty.\n"; 
} 

参考:如何检查PHP中是否只有字符串中的空格?

推荐阅读

Function get_magic_quotes_gpc() is deprecated报错解决办法

在 PHP 7.4 及更高版本中, get_magic_quotes_gpc() 函数已被弃用。 This means that code using this function will raise a warning or error.以下是解决......

PHP提示:Warning: count():Parameter must be an array or an object that implements Countable

错误原因:PHP7.2以后,count()函数的参数无效时会抛出warning警告。...

PHP7.4 报错:Deprecated Functionality: implode(): Passing glue string after array is deprecated.

PHP7.4运行项目报错:Deprecated Functionality: implode(): Passing glue string after array is deprecated。只需交换 implode() 函数的两个参数!...