【问题标题】:Why a function checking if a string is empty always returns true? [closed]为什么检查字符串是否为空的函数总是返回true? [关闭]
【发布时间】:2010-10-17 16:00:36
【问题描述】:

我有一个函数 isNotEmpty 如果字符串不为空则返回 true,如果字符串为空则返回 false。我发现如果我通过它传递一个空字符串,它就不起作用。

function isNotEmpty($input) 
{
    $strTemp = $input;
    $strTemp = trim($strTemp);

    if(strTemp != '') //Also tried this "if(strlen($strTemp) > 0)"
    {
         return true;
    }

    return false;
}

使用 isNotEmpty 验证字符串已完成:

if(isNotEmpty($userinput['phoneNumber']))
{
    //validate the phone number
}
else
{
    echo "Phone number not entered<br/>";
}

如果字符串为空则 else 不执行,我不明白为什么,请有人能解释一下。

【问题讨论】:

  • 只是一个建议:使用带有否定名称的函数通常是一种不好的做法。拥有函数 isEmpty($input) 更具可读性,否则你可能会这样称呼它: if (!isNotEmpty($x)) ... 另一方面,isNotEmpty() 和 (!isEmpty()) 不是那不同。 YMMV。
  • 拥有相同的功能而没有取反的名称,可能类似于 hasContent()。
  • !thatDifferent @johndodo
  • 这绝对是一个题外话:错字问题。

标签: php string validation


【解决方案1】:

其实很简单的问题。变化:

if (strTemp != '')

if ($strTemp != '')

您可能还想将其更改为:

if ($strTemp !== '')

因为!= '' 将返回true,如果你传递的是数字0 和其他一些情况,由于PHP's automatic type conversion

不应该为此使用内置的empty() 函数;请参阅 cmets 和 PHP type comparison tables

【讨论】:

  • 可以说,将 if 更改为:return $strTemp !== '';
  • 你不想使用empty()。考虑一串空格: $x = " "; var_dump(!empty($x)); /* (TRUE) / var_dump(isNotEmpty($x)); /(假)*/
  • OP 正在修剪字符串。在这种情况下是合适的。
  • @cletus:然后考虑一个字符串 $s='0'。如果您调用 empty($s) ,它将评估为 true(不直观,恕我直言,但确实如此)。
  • 不要使用empty()! empty() 将为诸如“0”之类的值返回 true。见 php.net/manual/en/types.comparisons.php
【解决方案2】:

我总是使用正则表达式来检查空字符串,可以追溯到 CGI/Perl 时代,也使用 Javascript,所以为什么不使用 PHP,例如(尽管未经测试)

return preg_match('/\S/', $input);

\S 代表任何非空白字符

【讨论】:

  • 这是这里唯一不假设零与空字符串相同的解决方案!
  • 很酷的解决方案。作为旁注,stackoverflow.com/a/4544642/5411817 提到:默认情况下 . 不匹配新行 - [\s\S] 是解决该问题的一个技巧。这在 JavaScript 中很常见,但在 PHP 中,您可以使用 /s 标志来使点匹配所有字符。 并且 stackoverflow.com/a/4544646/5411817 提到:(?s) 打开 s 模式并(?-s) 如果关闭则关闭。一旦关闭任何后续. 将不匹配换行符。如果你想打开/关闭开关内联(嵌入在正则表达式中)而不是作为正则表达式标志。
【解决方案3】:

PHP 有一个名为empty() 的内置函数 测试是通过键入完成的 if(empty($string)){...} 参考php.net:php empty

【讨论】:

  • 空参考已经在 cletus 接受的答案的末尾。另请参阅此问答线程来自 2009 年 4 月。无论如何,感谢您的输入。我给你一个 +1 的第一个答案。
  • 不要使用empty()! empty() 将为诸如“0”之类的值返回 true。见php.net/manual/en/types.comparisons.php
  • @ScottDavidTesler 如果字符串为“0”,它会返回 true 吗?还是仅当它是整数 0 时?
  • @TomasZubiri 是的,包含“0”的字符串将返回true。
  • 拜托,没有其他人支持这个错误的答案 - 阅读上面的 cmets!
【解决方案4】:

在函数的if 子句中,您指的是不存在的变量strTemp。不过,$strTemp 确实存在。

但是 PHP 已经有一个可用的empty() 函数;为什么要自己做?

if (empty($str))
    /* String is empty */
else
    /* Not empty */

来自 php.net:

返回值

如果 var 有一个非空值,则返回 FALSE 和非零值。

考虑以下几点 为空:

* "" (an empty string)
* 0 (0 as an integer)
* "0" (0 as a string)
* NULL
* FALSE
* array() (an empty array)
* var $var; (a variable declared, but without a value in a class)

http://www.php.net/empty

【讨论】:

  • 并非所有实现都希望将“0”评估为空。如果他想要这样,他就不能使用 if($x) 比较,即 If(!trim($str)) 吗?
  • 请注意,执行 $tmpStr != '' 也会返回 true 的 $tmpStr 持有 0 或 false 或另一个空/false 值。
  • 您的版本实际上不起作用:空适用于变量,而不适用于表达式。
【解决方案5】:

PHP 将空字符串评估为 false,因此您可以简单地使用:

if (trim($userinput['phoneNumber'])) {
  // validate the phone number
} else {
  echo "Phone number not entered<br/>";
}

【讨论】:

  • 这工作正常,直到你通过 0。否则这个想法很棒,我会在其他地方使用它。感谢您的回复。
【解决方案6】:

只需使用 strlen() 函数

if (strlen($s)) {
   // not empty
}

【讨论】:

  • 这取决于 PHP 如何实现 strlen() 函数。例如,在 Delphi 中,字符串实际上已经存储了它的长度减去 4 字节偏移量,因此检查它的长度是微不足道的。
  • 不输入保存。在Php 5.3 之前,如果$s 的类型为array,该函数将返回5Php &gt; 5.3 将引发异常。我推荐使用is_string($s) &amp;&amp; str_len($s) &gt; 0&gt;0 仅供阅读。
【解决方案7】:

我只是编写自己的函数,is_string 用于类型检查,strlen 用于检查长度。

function emptyStr($str) {
    return is_string($str) && strlen($str) === 0;
}

print emptyStr('') ? "empty" : "not empty";
// empty

Here's a small test repl.it

编辑:您还可以使用trim 函数来测试字符串是否也是空白。

is_string($str) && strlen(trim($str)) === 0;    

【讨论】:

    【解决方案8】:

    我需要在 PHP 中测试一个空字段并使用

    ctype_space($tempVariable)
    

    这对我来说效果很好。

    【讨论】:

    • 这是另一个问题的正确答案。此答案不检查字符串是否为空。
    【解决方案9】:

    这里是检查字符串是否为空的简短方法。

    $input; //Assuming to be the string
    
    
    if(strlen($input)==0){
    return false;//if the string is empty
    }
    else{
    return true; //if the string is not empty
    }
    

    【讨论】:

    • 2014 年在此页面上建议检查 strlen()。您的回答没有增加任何新价值。
    【解决方案10】:

    您可以简单地转换为 bool,不要忘记处理零。

    function isEmpty(string $string): bool {
        if($string === '0') {
            return false;
        }
        return !(bool)$string;
    }
    
    var_dump(isEmpty('')); // bool(true)
    var_dump(isEmpty('foo')); // bool(false)
    var_dump(isEmpty('0')); // bool(false)
    

    【讨论】:

    • (bool)$str!empty($str) 一样,和'0' 有同样的问题。阅读PHP Booleans,“转换为布尔值”部分。另外,你把它弄反了——应该是!(bool)$string'。或者你的函数应该命名为“isNotEmpty”。无论如何,您都被错误地处理 '0' 所困扰。
    • @ToolmakerSteve 对于0 问题,只需在返回转换后的字符串之前处理它。非常感谢,我忘记了否定!(否定函数名称是不好的做法)。编辑了我的帖子。
    【解决方案11】:

    我知道这个帖子已经很老了,但我只是想分享我的一个功能。下面的这个函数可以检查空字符串、最大长度的字符串、最小长度或精确长度。如果要检查空字符串,只需将 $min_len 和 $max_len 设置为 0。

    function chk_str( $input, $min_len = null, $max_len = null ){
    
        if ( !is_int($min_len) && $min_len !== null ) throw new Exception('chk_str(): $min_len must be an integer or a null value.');
        if ( !is_int($max_len) && $max_len !== null ) throw new Exception('chk_str(): $max_len must be an integer or a null value.'); 
    
        if ( $min_len !== null && $max_len !== null ){
             if ( $min_len > $max_len ) throw new Exception('chk_str(): $min_len can\'t be larger than $max_len.');
        }
    
        if ( !is_string( $input ) ) {
            return false;
        } else {
            $output = true;
        }
    
        if ( $min_len !== null ){
            if ( strlen($input) < $min_len ) $output = false;
        }
    
        if ( $max_len !== null ){
            if ( strlen($input) > $max_len ) $output = false;
        }
    
        return $output;
    }
    

    【讨论】:

      【解决方案12】:

      如果您有一个名为 serial_number 的字段并且想要检查为空,那么

      $serial_number = trim($_POST[serial_number]);
      $q="select * from product where user_id='$_SESSION[id]'";
      $rs=mysql_query($q);
      while($row=mysql_fetch_assoc($rs)){
      if(empty($_POST['irons'])){
      $irons=$row['product1'];
      }
      

      通过这种方式,您可以使用另一个空函数检查循环中的所有文件

      【讨论】:

      • empty() 早在 2009 年就已在此页面上推荐过。
      【解决方案13】:

      这是简短而有效的解决方案,正是您正在寻找的:

      return $input > null ? 'not empty' : 'empty' ;
      

      【讨论】:

      • 我还没有测试这是否有效,但如果有效,它将通过将null 转换为空字符串进行比较。在这种情况下,说出你的意思会更清楚:$input &gt; ''。也就是说,“在输入字符串和空字符串之间进行词法比较”。或者忽略末尾的空格:trim($input) &gt; ''.
      • ... 还需要测试$input'0' 时会发生什么。当第一个参数是数字字符串时,不清楚php是否进行numericlexical比较。
      【解决方案14】:

      你得到了答案,但在你的情况下你可以使用

      return empty($input);
      

      return is_string($input);
      

      【讨论】:

      • empty("0") 失败
      • @geekido - 否决错误答案是 StackOverflow 的一部分 - 它会将这些答案向下移动,并鼓励回答者更正或删除他们的答案。你明白你的答案有什么问题吗? 1. empty - 这个答案已经给出,所以再说一遍不会有任何贡献。更糟糕的是,正如 cmets 中所讨论的,这是错误的 - 任何等于 0 的值都将被视为“空”。 2. is_string 以不同的方式出错 - 一个空字符串 '' 是一个字符串,所以在这种情况下将返回 true - 无法按照问题的要求进行操作。
      猜你喜欢
      • 1970-01-01
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      • 2012-02-06
      相关资源
      最近更新 更多