PHP中的标签验证 - 允许输入字段为空?

时间:2014-10-18 18:20:59

标签: php

剧本:

<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
    <input type="text" name="hashtag1" />
    <input type="text" name="hashtag2" />
    <input type="text" name="hashtag3" />
    <input type="text" name="hashtag4" />

    <input type="submit" name="submit" />
</form>

<?php

if(isset($_POST['submit'])){

    if(isset($_POST['hashtag1'])) {
        $hashtag1 = $_POST['hashtag1'];
    }
    if(isset($_POST['hashtag2'])){
        $hashtag2 = $_POST['hashtag2'];
    }
    if(isset($_POST['hashtag3'])){
        $hashtag3 = $_POST['hashtag3'];
    }
    if(isset($_POST['hashtag4'])){
        $hashtag4 = $_POST['hashtag4'];
    }

    $myarray = array($hashtag1, $hashtag2, $hashtag3, $hashtag4);

    for($i = 0; $i < count($myarray); $i++){

        if(!preg_match('/^(?=.{2,140}$)(#|\x{ff03}){1}([0-9_\p{L}]*[_\p{L}][0-9_\p{L}]*)$/u', $myarray[$i])){
            echo "Please check your hashtags!";
            exit;
        }

    }

    function array_has_dupes($array) {
        return count($array) !== count(array_unique($array));
    }

    if(array_has_dupes($myarray) == true){
        echo "Please make sure you do not have duplicate hashtags!";
        exit;
    }

    echo "Hello World!";

}

?>

当我将那些四个输入字段的输入字段留空时, 然后 我得 &#34;请检查您的主题标签。&#34; 打印在屏幕上。

我的问题是,如何修改脚本以便将一个或多个输入字段留空?

我正在使用&#34; PHP Twitter Hashtag Validation Regex&#34;来自GitHub:link

1 个答案:

答案 0 :(得分:2)

使用变量跟踪有效的主题标签,在循环之前将其定义为false。如果您找到有效的主题标签,请跳出循环并将变量设置为true

循环后,检查变量,如果它仍然为假,则显示错误并退出:

$atLeastOne = false;
for($i = 0; $i < count($myarray); $i++){
    if(preg_match('/^(?=.{2,140}$)(#|\x{ff03}){1}([0-9_\p{L}]*[_\p{L}][0-9_\p{L}]*)$/u', $myarray[$i])){
        $atLeastOne = true;
        break;
    }
}
if(!$atLeastOne){
    echo "Please check your hashtags!";
    exit;
}

请注意,我们在此处检查有效主题标签,因此您需要从!声明中删除if