如何确定某物是否不是字符串以及某物是否为空?

时间:2018-10-08 12:00:20

标签: php string get

在我的PHP中,我有2个可选输入。 input1=input2=。两者都是可选输入。我的问题是如何确定只是不提供输入还是提供的输入不是字符串?

我只希望人们输入一个实际的字符串。没有不同类型的数据结构。

示例

有效:www.example.com/myfile.php?input1=hello&input2=bye

有效:www.example.com/myfile.php?input1=hello

有效:www.example.com/myfile.php?input2=hello

有效:www.example.com/myfile.php

无效:www.example.com/myfile.php?input1[]


<?php

function check_valid($string) {
    if (!is_string($string)) {
        echo "This is a not string. We tested: ".$string."<br>";
    } else {
        echo "This is is string. We tested: ".$string."<br>";
    }
}

$input1 = check_valid($_GET['input1']);
$input2 = check_valid($_GET['input2']);
?>

2 个答案:

答案 0 :(得分:0)

您应该使用isset()方法检查是否提供了$ input1或$ input2。

function check_valid($test) {
    if (isset($test) && is_string($test)) {
        echo "Valid";
        return;
    }
    echo "Not Valid";
}

答案 1 :(得分:0)

您可以检查值是否存在,是否包含空值或null。

<?php

function check_valid($string) {
    if (trim($string) == NULL OR trim($string) == "") { //Will check if value without a space is null or empty         
        return "valid";

    } 
} 
$input1 = check_valid($_GET['input1']);
$input2 = check_valid($_GET['input2']);
?>