簡體   English   中英

如何檢查 PHP 中的數據是否為空或空白

[英]How to check if data is empty or whitespace only in PHP

我有一個需要用戶名的輸入字段。 場景是,我如何防止用戶在該字段中提供空格或空格? 我已經在輸入字段中添加了required ,因此我可以防止用戶將其留空。

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

但是,如果用戶放置空格或盡可能多的空格怎么辦,我有什么可能的方法可以檢測到這一點並向用戶拋出錯誤嗎?

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

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

但這將失敗,因為用戶在輸入字段中輸入了空格。

你可以這樣做。

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

你可以使用trimstrlen php函數

試試這個....

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

我認為str_replace()就是你想要的。 或者您可以使用一些javascript來防止將空格輸入到輸入字段中。

<?php
$s = str_replace(' ', '', $_POST['username']);
?>

如果您打算使用trim() ,請不要忘記rtrim()

你可以在提交表單之前使用$ .trim()jquery函數。

var nowhitespace = $.trim($("#input").val());

我可以看到這是一個很老的問題,但在搜索一種方法來檢查字符串是否只包含空白字符時,它仍然排在最前面的結果中。

PHP trim 方法(以及ctype_space等其他方法)實際上並沒有刪除所有可能的空白字符。 修剪只刪除:

" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\v" (ASCII 11 (0x0B)), a vertical tab.

(全部復制自https://www.php.net/manual/en/function.trim.php

並且wiki指定了大約 32 個空白字符(其中 6 個僅與空白相關但標記為非空白,因此該表分為兩組,您決定是否需要第二組)

然后檢查字符串是否只包含空格:

// BE AWARE that I'm assuming that text is in UTF-8 (which will be probably true in most cases) 
/**
 * Find the end of the UTF-8 char
 * https://stackoverflow.com/a/14366023/11495586
 * @param  string $string     UTF-8 string
 * @param  int    $pointer    Start of the character (byte)
 * @param  int    $nextLetter Reference to save where next character starts
 * @return string             Whole letter
 */
function get(string $string, int $pointer, int &$nextLetter): string|bool
{
    if (!isset($string[$pointer])) {
        return false;
    }

    $char = ord($string[$pointer]);

    if ($char < 128) {
        $nextLetter = $pointer + 1;
        return $string[$pointer];
    }

    if ($char < 224) {
        $bytes = 2;
    } elseif ($char < 240) {
        $bytes = 3;
    } else {
        $bytes = 4;
    }
    $str = substr($string, $pointer, $bytes);
    $nextLetter = $pointer + $bytes;
    return $str;
}


function isWhitespace(string $string): bool
{
    if (strlen($string) == 0) {
        return false;
    }

    // https://en.wikipedia.org/wiki/Whitespace_character
    $table = [
        // Unicode characters with property White_Space=yes
        "\u{0009}" => true, "\u{000A}" => true, "\u{000B}" => true, "\u{000C}" => true,
        "\u{000D}" => true, "\u{0020}" => true, "\u{0085}" => true, "\u{00A0}" => true,
        "\u{1680}" => true, "\u{2000}" => true, "\u{2001}" => true, "\u{2002}" => true,
        "\u{2003}" => true, "\u{2004}" => true, "\u{2005}" => true, "\u{2006}" => true,
        "\u{2007}" => true, "\u{2008}" => true, "\u{2009}" => true, "\u{200A}" => true,
        "\u{2028}" => true, "\u{2029}" => true, "\u{202F}" => true, "\u{205F}" => true,
        "\u{3000}" => true,
        // Related Unicode characters with property White_Space=no
        "\u{180E}" => true, "\u{200B}" => true, "\u{200C}" => true, "\u{200D}" => true,
        "\u{2060}" => true, "\u{FEFF}" => true,
    ];
    $nextLetter = $i = 0;

    // Iterate over the string and cut it into proper UTF-8 letters
    // We have to do this to have actual letters and not letters chunked into bytes
    // as they will be saved in multiple spaces, so spliting text by 1 with substr
    // will only return in trash characters if we encounter something that has length
    // bigger then 1 byte
    //
    // If you have mbstring extension installed you might want to use mb_substr but this
    // will be a lot slower as for each cut it will iterate over the string (again from the start)
    // to cut it into properly sized chunks. Have a read:
    // https://www.php.net/manual/en/function.mb-substr.php - note from `qbolec at gmail dot com`
    while (($letter = get($string, $i, $nextLetter)) !== false) {
        // Quick exit if any char is not whitespace to prevent additional loops
        if (!isset($table[$letter])) {
            return false;
        }
        $i = $nextLetter;
    }

    return true;
}

用法:

isWhitespace("\t\n\r");  // true
isWhitespace("\td\n\r"); // false
isWhitespace("");        // false
// This one is "\u{2003}\u{2000}\u{2009}" (em space, en quad and thin space) but in UTF-8
isWhitespace("   ");     // true

要檢查某物是否為空,您可以使用empty方法:

if (empty($string)) {
    // Is empty!
}

如果您不想在每個項目中手動將字符串分成適當的字母(像我一樣),您可能想使用我的庫 - https://github.com/Mortimer333/Content

//Ensure there's a space between the inverted commas
if(empty($_POST['firstname']) || $_POST['Firstname'] = " "){
echo "cannot be empty";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM