简体   繁体   English

在PHP中嵌套if else语句以验证URL

[英]Nesting if else statements in PHP to validate a URL

I'm currently writing up a function in order to validate a URL by exploding it into different parts and matching those parts with strings I've defined. 我目前正在编写一个函数,以便通过将URL扩展到不同的部分并使用我定义的字符串匹配这些部分来验证URL。 This is the function I'm using so far: 这是我到目前为止使用的功能:

function validTnet($tnet_url) {
    $tnet_2 = "defined2";
    $tnet_3 = "defined3";
    $tnet_5 = "defined5";
    $tnet_7 = "";

    if($exp_url[2] == $tnet_2) {
        #show true, proceed to next validation

        if($exp_url[3] == $tnet_3) {
        #true, and next

                if($exp_url[5] == $tnet_5) {
                #true, and last

                        if($exp_url[7] == $tnet_7) {
                        #true, valid
                        }
                }
            }
    } else {
        echo "failed on tnet_2";
    }
}

For some reason I'm unable to think of the way to code (or search for the proper term) of how to break out of the if statements that are nested. 出于某种原因,我无法想到如何打破嵌套的if语句的代码(或搜索正确的术语)。

What I would like to do check each part of the URL, starting with $tnet_2 , and if it fails one of the checks ( $tnet_2 , $tnet_3 , $tnet_5 or $tnet_7 ), output that it fails, and break out of the if statement. 我想做的是检查URL的每个部分,从$tnet_2开始,如果它没有通过其中一个检查( $tnet_2$tnet_3$tnet_5$tnet_7 ),输出它失败,并突破如果声明。 Is there an easy way to accomplish this using some of the code I have already? 有没有一种简单的方法可以使用我已经拥有的一些代码来实现这一目标?

$is_valid = true;

foreach (array(2, 3, 5, 7) as $i) {
    if ($exp_url[$i] !== ${'tnet_'.$i}) {
        $is_valid = false;
        break;   
    }
}

You could do $tnet[$i] if you define those values in an array: 如果在数组中定义这些值,则可以执行$tnet[$i]

$tnet = array(
  2 => "defined2",
  3 => "defined3",
  5 => "defined5",
  7 => ""
);

Combine all the if conditions 结合所有if条件

if(
   $exp_url[2] == $tnet_2 && 
   $exp_url[3] == $tnet_3 && 
   $exp_url[5] == $tnet_5 && 
   $exp_url[7] == $tnet_7
) {
  //true, valid
} else {
  echo "failed on tnet_2";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM