将变量的前6位数字与数组中的多个字符串匹配(PHP)

将变量的前6位数字与数组中的多个字符串匹配(PHP),php,Php,我正在尝试使用preg_match和其他有用的东西进行比较或匹配 我有这个阵列: $ids = array("93215018" ,"93215019" ,"93215020" ,"93215022" ,"93215025" ,"93215040" ,"93215050","93215079" ,"93215070"

我正在尝试使用preg_match和其他有用的东西进行比较或匹配

我有这个阵列:

$ids = array("93215018" ,"93215019" ,"93215020" ,"93215022" ,"93215025" 
,"93215040" ,"93215050","93215079" ,"93215070" ,"93215021" ,"93935018" 
,"93935019" ,"93935020" ,"93935022" ,"93935025" ,"93935040" ,"93935050" 
,"93935079" ,"93935070" ,"93935021" ,"93415018" ,"93415019" ,"93415020" 
,"93415022" ,"93415025" ,"93415040" ,"93415050" ,"93415079" ,"93415070" 
,"93415021" ,"93515018" ,"93515019" ,"93515020" ,"93515022" ,"93515025" 
,"93515040" ,"93515050" ,"93515079" ,"93515070" ,"93515021" ,"93615018" 
,"93615019" ,"93615020" ,"93615022" ,"93615025" ,"93615040" ,"93615050" 
,"93615079" ,"93615070" ,"93615021" ,"93715018" ,"93715019" ,"93715020" 
,"93715022" ,"93715025" ,"93715040" ,"93715050" ,"93715079" ,"93715070" 
,"93715021");
我制作了一个变量,它使用HTML从输入表单获取ID:

现在,当用户输入ID时,PHP文件应该检查他输入的前7位数字是否与数组中定义的前7位数字匹配

我用过这些东西,但没用:

$first7 = substr($uid, 7);
foreach($ids as $id) {
    $firstid = substr($id, 7);
    $pos = strpos($firstid, $first7);
    if ($pos !== true) {
        header("Location: success.php"); 
    } 
}
以及:

以及:

以及:

还是不起作用


有人知道怎么做吗??我使用的是PHP 5.6..

您可以尝试以下简单的解决方案:

$first7 = substr($uid, 0, 7);

$matched = false;

foreach ($ids as $id) {

    if (substr($id, 0, 7) === $first7) {
        $matched = true;
        break;
    }
}
substr$uid,7;这不是你得到前7个字符的方式。的第二个参数是起始位置,而不是长度

另外,如果您已经获得了$uid的前七个字符和数组项的前七个字符,则根本不需要使用strpos。你可以检查他们是否相等

您可以使用它来获取$uid的前七个字符:

然后您可以找到所有匹配的ID

$matches = preg_grep("/^$first7/", $ids);
或在找到第一个后重定向:

foreach($ids as $id) {
    $firstid = substr($id, 0, 7);
    if ($firstid === $first7) {
        header("Location: success.php");
        exit;
    }

}

它不起作用是没有帮助的。发生了什么事?结果与你想要的有什么不同?你有错误吗?如果是,它们是什么?strpos将永远不会返回true。如果找不到任何内容或找到的位置的索引,则返回FALSE。@abracadve Me!虽然如果有很多值,最好使用另一个在找到一个匹配项后中断的答案。这样做非常有效。。。你下面的答案同样有效。。谢谢大家在为if条件添加else语句后,在不检查if条件的情况下不会执行else语句。。有没有办法解决这个问题?@BHappy如果你想重定向到其他地方,如果找不到,不要把它放在else块中。把它放在foreach循环之后。如果在循环过程中找到它,它将立即重定向,如果它在循环结束时没有找到它,它将重定向到另一个位置。当我在没有else条件的情况下使用它时,代码在添加else条件后立即工作,因为总是在不检查If条件的情况下执行else。。我的else是simple else{headerLocation:failed.php;
$first7 = substr($uid, 0, 7);

$matched = false;

foreach ($ids as $id) {

    if (substr($id, 0, 7) === $first7) {
        $matched = true;
        break;
    }
}
$first7 = substr($uid, 0, 7);
$matches = preg_grep("/^$first7/", $ids);
foreach($ids as $id) {
    $firstid = substr($id, 0, 7);
    if ($firstid === $first7) {
        header("Location: success.php");
        exit;
    }

}