IT

null 또는 빈 문자열에 대한 변수를 확인하는 더 좋은 방법은 무엇입니까?

lottoking 2020. 5. 27. 07:51
반응형

null 또는 빈 문자열에 대한 변수를 확인하는 더 좋은 방법은 무엇입니까?


PHP는 동적 언어이므로 제공된 필드가 비어 있는지 확인하는 가장 좋은 방법은 무엇입니까?

나는 그것을 보장하고 싶다 :

  1. null은 빈 문자열로 간주됩니다
  2. 공백 만있는 문자열은 비어있는 것으로 간주됩니다.
  3. "0"은 비어있는 것으로 간주되지 않습니다

이것이 내가 지금까지 얻은 것입니다.

$question = trim($_POST['question']);

if ("" === "$question") {
    // Handle error here
}

이 작업을 수행하는 더 간단한 방법이 있어야합니까?


// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
    return (!isset($str) || trim($str) === '');
}

오래된 게시물이지만 누군가가 내가 한 것처럼 필요할 수도 있습니다.)

if (strlen($str) == 0){
do what ever
}

$str변수로 대체 하십시오. NULL""사용할 때 둘 다 0을 반환 strlen합니다.


PHP의 empty () 함수를 사용하십시오. 다음은 비어있는 것으로 간주됩니다

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

자세한 내용은 빈 기능 확인


내가 틀렸다면 겸손히 받아 들일 것이지만, 나는 내 자신의 목적으로 테스트했으며 string (0) ""및 NULL 값 변수를 테스트하는 데 다음이 작동한다는 것을 알았습니다.

if ( $question ) {
  // Handle success here
}

성공 여부를 테스트하기 위해 되돌릴 수도 있습니다.

if ( !$question ) {
  // Handle error here
}

trim()함수 에서 오 탐지에주의하십시오. 트리밍하기 전에 문자열로 캐스트를 수행하므로 빈 배열을 전달하면 "Array"를 반환합니다. 데이터를 처리하는 방법에 따라 문제가되지는 않지만 제공 한 코드를 사용 question[]하면 POST 데이터에 이름 지정된 필드 가 제공 될 수 있으며 비어 있지 않은 문자열로 나타납니다. 대신, 나는 제안 할 것이다 :

$question = $_POST['question'];

if (!is_string || ($question = trim($question))) {
    // Handle error here
}

// If $question was a string, it will have been trimmed by this point

더 좋은 방법은 없지만 일반적으로 수행하는 작업이므로 프로세스를 자동화하는 것이 좋습니다.

대부분의 프레임 워크는 인수를 쉽게 분석 할 수있는 방법을 제공합니다. 당신은 그 자신의 객체를 만들 수 있습니다. 빠르고 더러운 예 :

class Request
{

    // This is the spirit but you may want to make that cleaner :-)
    function get($key, $default=null, $from=null)
    {
         if ($from) :
             if (isset(${'_'.$from}[$key]));
                return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
         else
             if isset($_REQUEST[$key])
                return sanitize($_REQUEST[$key]);

         return $default;
    }

    // basics. Enforce it with filters according to your needs
    function sanitize($data)
    {
          return addslashes(trim($data));
    }

    // your rules here
    function isEmptyString($data)
    {
        return (trim($data) === "" or $data === null);
    }


    function exists($key) {}

    function setFlash($name, $value) {}

    [...]

}

$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);

심포니는 그런 종류의 설탕을 대량으로 사용합니다.

But you are talking about more than that, with your "// Handle error here ". You are mixing 2 jobs : getting the data and processing it. This is not the same at all.

There are other mechanisms you can use to validate data. Again, frameworks can show you best pratices.

Create objects that represent the data of your form, then attach processses and fall back to it. It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code.


to be more robust (tabulation, return…), I define:

function is_not_empty_string($str) {
    if (is_string($str) && trim($str, " \t\n\r\0") !== '')
        return true;
    else
        return false;
}

// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
    var_export($value);
    if (is_not_empty_string($value)) 
        print(" is a none empty string!\n");
    else
        print(" is not a string or is an empty string\n");
}

sources:


This one checks arrays and strings:

function is_set($val) {
  if(is_array($val)) return !empty($val);

  return strlen(trim($val)) ? true : false;
}

When you want to check if a value is provided for a field, that field may be a string , an array, or undifined. So, the following is enough

function isSet($param)
{
    return (is_array($param) && count($param)) || trim($param) !== '';
}

empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:

if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {

참고URL : https://stackoverflow.com/questions/381265/better-way-to-check-variable-for-null-or-empty-string

반응형