如何仅在 PHP 中检查数据是否为空或空白 [英] How to check if data is empty or whitespace only in PHP

查看:29
本文介绍了如何仅在 PHP 中检查数据是否为空或空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要用户名的输入字段.场景是,如何防止用户在该字段中提供空格或空格?我已经在输入字段中添加了 required 以便我可以防止用户将其留空.

I have an input field that needs a username. The scenario is, how can i prevent user from providing whitespace or whitespaces in the that field? I already added required in the input field so i can prevent user from leaving it blank.

<input type="text" name="username" required>

但是如果用户输入空格或尽可能多的空格怎么办,我有什么可能的方法可以检测到这一点并向用户抛出错误?

but what if the user puts whitespace or as many whitespace as he can, is there any possible way i can detect this and throw error to the user?

在我的 php 文件中我已经有了

in my php file i already have

if(empty($_POST['username'])){
echo "Username should not be empty!";
}

但是由于用户在输入字段中放置了空格,这将失败.

but this will fail because of the whitespaces the users put in the input field.

推荐答案

你可以这样做.

if(isset($_POST['username']))
{
    if(strlen(trim($_POST['username']))<=0){
    echo "Username should not be empty!";
    }
}

这篇关于如何仅在 PHP 中检查数据是否为空或空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆