dongwu8653 2014-10-18 18:20
浏览 45
已采纳

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

The Script:

<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!";

}

?>

When I leave one input field of those four input fields empty, then I get "Please check your hashtags." printed on screen.

My question is, how to modify the script so leaving one or more input fields empty is allowed?

I am using the "PHP Twitter Hashtag Validation Regex" from GitHub: link

  • 写回答

1条回答 默认 最新

  • dongtang1997 2014-10-18 18:24
    关注

    Use a variable to keep track of a valid hashtag, define it as false before your loop. If you find a valid hashtag, break out of your loop and set your variable to true.

    After your loop, check the variable and if it's still false, display your error and exit:

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

    Note we are checking for a valid hashtag here, so you need to remove ! from within your if statement.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CATIA有些零件打开直接单机确定终止
  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址