php脚本匹配数组中字符串的给定部分

时间:2013-12-07 10:41:04

标签: php arrays pattern-matching

我有一个像"123456-1234-001-N"和数组$ids = array("123456-1234-002-N","123456-1234-001-S","4567789-4567-004-S","457896-14578-007-W")

这样的字符串

我想比较数组中的字符串,找出字符串的哪些剩余部分不匹配,例如:

  • 案例1 :123456,1234和N在数组中,但在第一种情况下001不匹配,因此抛出错误消息

  • 案例2 :123456,1234和001出现在数组中,第二种情况N不匹配,因此会抛出错误消息。

    感谢任何帮助!

更新1: 脚本应匹配数组中的整个字符串并显示错误消息,指出第三个或第四个垃圾不匹配。例如:我们可以使用123456和1234的字符串,看看001是匹配还是N匹配。基本上我需要知道字符串的第三/第四部分是否匹配。

更新2: 我从接受的答案中选择了第二种方法!

1 个答案:

答案 0 :(得分:1)

好的,到你最新的编辑:

$search = "123456-1234-001-N";
$ids = array("123456-1234-002-N","123456-1234-001-S","4567789-4567-004-S","457896-14578-007-W");

$search_parts = explode('-', $search);

foreach ( $ids as $id ) {
    echo "Checking {$id}..." . PHP_EOL;
    $id_parts = explode('-', $id);
    $i = 0;
    $is_correct = true;
    foreach ( $search_parts as $part ) {
        $part_no = $i + 1;
        if ( $part != $id_parts[$i] ) {
            $is_correct = false;
            echo "  part number {$part_no} is incorrect (is: {$id_parts[$i]}, should be: {$part});" . PHP_EOL;
        }
        $i++;
    }
    if ( $is_correct ) {
        echo "  This is a correct id!" . PHP_EOL;
    }
    echo PHP_EOL;
}

使用preg_match完成同样的事情(差不多):

$search = "123456-1234-001-N";

$search_pattern = '/^([0-9]*)\\-([0-9]*)\\-([0-9]*)\\-([A-Z]*)$/';
$ids = array("123456-1234-002-N","123456-1234-001-S","4567789-4567-004-S","457896-14578-007-W");

$search_parts = explode('-', $search);
foreach ( $ids as $id ) {
    $res = preg_match($search_pattern, $id, $matches);
    if ( ! $res ) {
        throw new Exception("The id {$id} is in invalid format");
    }
    $diff = array_diff($search_parts, $matches);
    printDiffMessage($diff);
    echo PHP_EOL . "----" . PHP_EOL;
}

function printDiffMessage(array $diff)
{
    foreach ( $diff as $key => $value ) {
        $pos = $key + 1;
        echo "Keys differ at position {$pos}. ";
    }
}

上一篇(仅供参考):

试试这段代码:

$ids = array("123456-1234-002-N","123456-1234-001-S","4567789-4567-004-S","457896-14578-007-W");

$search = '123456-1234-001-N';

foreach ( $ids as $single_id ) {
    $match = '';
    $i = 0;
    foreach ( str_split($search) as $chr ) {
        if ( $single_id[$i] != $chr ) {
            break;
        }
        $match .= $chr;
        $i++;
    }
    var_dump($match);
}

这是你想要做的吗?

要进行编辑:似乎in_array就是您所需要的。

if ( in_array($search, $ids) ) {
    echo "Found it";
}
else {
    echo "Error message";
}