PHP - 将字符串的第1个字符与数组值和返回键匹配

时间:2017-06-15 19:47:27

标签: php regex

我有大量数据

clipboard.js

和一个数组:( Key => Val)

0134234XXX
0255234XXX
0843324XXX
080054XXXX
001342343XX
07800XXXXXX
003342343XX

我正在尝试编写一个函数,它将返回匹配的第1个字符的Key 例如:

[1] => [01]
[2] => [001]
[3] => [07]
[4] => [0845]

2 个答案:

答案 0 :(得分:0)

你不需要这里的正则表达式:

$findKey = function($str) use ($values) {
    foreach ($values as $k => $v)
        if (strpos($str, $v) === 0) return $k;
    return false;
};

Live demo

答案 1 :(得分:0)

我不认为OP想要一个匿名函数,因为它可以在数组元素上重用。

这是一种效率稍低的revo方法,当搜索数组值也作为另一个值的前导字符存在时,它将寻找最长的匹配。 (Demo

$tin_foil_hat="on";  // <-- essential for this method ;)

function findkey($haystack,$needles){
    $match=0; // "No Match";
    foreach($needles as $k=>$v){
        if(strpos($haystack,$v)===0){
            $match=$k;  // overwrite any shorter previous matches
        }
    }
    return $match;
}

$haystacks=['0134234XXX','0255234XXX','0843324XXX','080054XXXX','001342343XX','07800XXXXXX','003342343XX'];
$haystacks[]='0110000XXX'; // for Wiktor
$needles=[1=>'01',2=>'001',3=>'07',4=>'0845'];
$needles[5]='011'; // for Wiktor
// This assumes shorter string contained in a larger string will be ordered first in $needles array.
// If no needles value is contained in another needles value, then revo's is the way to go (with early return).

foreach($haystacks as $haystack){
     echo $haystack,' => ',findkey($haystack,$needles),"\n";
}

输出:

0134234XXX => 1
0255234XXX => 0
0843324XXX => 0
080054XXXX => 0
001342343XX => 2
07800XXXXXX => 3
003342343XX => 0
0110000XXX => 5