programing

문자열이 비어 있는지 확인하는 함수가 항상 true를 반환하는 이유는 무엇입니까?

copysource 2023. 1. 14. 10:26
반응형

문자열이 비어 있는지 확인하는 함수가 항상 true를 반환하는 이유는 무엇입니까?

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/>";
}

만약 문자열이 비어있으면 다른 문자열이 실행되지 않는다면, 왜 그런지 모르겠습니다만, 누군가 이것을 좀 밝혀 주실 수 있겠습니까?

사실 간단한 문제죠.변경:

if (strTemp != '')

로.

if ($strTemp != '')

다음과 같이 변경할 수도 있습니다.

if ($strTemp !== '')

부터!= ''숫자 0을 통과하면 true가 반환되며 PHP의 자동 유형 변환으로 인해 몇 가지 다른 경우가 반환됩니다.

이 경우 삽입 empty() 함수를 사용하지 마십시오.댓글과 PHP 유형 비교 표를 참조하십시오.

CGI/Perl days 및 Javascript에서 빈 문자열을 체크할 때는 항상 정규 표현을 사용합니다.따라서 (테스트되지 않았지만) PHP에서도 마찬가지입니다.

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

어디에\S공백 이외의 문자를 나타냅니다.

PHP에는 다음과 같은 함수가 내장되어 있습니다.empty()테스트는 타이핑으로 이루어집니다.if(empty($string)){...}참조 php.net : php가 비어 있습니다.

고객님의 고객명if함수의 절은 변수를 참조하고 있습니다.strTemp그런 건 없어요 $strTemp존재하긴 하지만요

그러나 PHP는 이미empty()기능을 이용할 수 있습니다.왜 당신만의 기능을 만들까요?

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

php.net 에서 :

반환값

var의 값이 비어 있지 않고 0이 아닌 경우 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

PHP는 빈 문자열을 false로 평가하므로 다음과 같이 간단히 사용할 수 있습니다.

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

strlen() 함수를 사용합니다.

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

유형체크용 is_string, 길이체크용 strlen 등 나만의 함수를 작성하기만 하면 됩니다.

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

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

여기 작은 테스트가 있습니다.repl.it

EDIT: 트리밍 기능을 사용하여 문자열이 공백인지 테스트할 수도 있습니다.

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

PHP에서 빈 필드를 테스트해야 했고

ctype_space($tempVariable)

잘 먹혔어요.

여기 문자열이 비어 있는지 확인하는 간단한 방법이 있습니다.

$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
}

간단히 Bool로 캐스팅할 수 있습니다. 0을 다루는 것을 잊지 마십시오.

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)

이 스레드가 꽤 오래되었다는 것을 알지만, 나는 단지 내 기능 중 하나를 공유하고 싶었다.다음 함수는 빈 문자열, 최대 길이, 최소 길이 또는 정확한 길이를 확인할 수 있습니다.빈 문자열을 확인하려면 $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;
}

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'];
}

이렇게 하면 다른 빈 함수로 루프 내의 모든 필라드를 체크할 수 있습니다.

이것이 바로 여러분이 찾고 있는 간단하고 효과적인 솔루션입니다.

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

답을 얻었지만, 당신의 경우에는

return empty($input);

또는

return is_string($input);

언급URL : https://stackoverflow.com/questions/718986/why-a-function-checking-if-a-string-is-empty-always-returns-true

반응형