我需要一个PHP函数,我可以匹配数组中的字符串,只返回匹配的部分。
描述
38001,38002,38003 应返回3800
38001,38002,38010 应返回380
f38001,f38002,f38100 应该返回f38
感谢您的回答。
答案 0 :(得分:1)
使用这三个$numbers
数组测试此例程。
$numbers = array(38021, 38002, 38003);
$numbers = array(38021, 38221, 38003);
$numbers = array(380010, 38001, 38010);
$numbers = array('f38001','f38102','f38100');
将使用数组中的任意数量的字符串。
将使用最多999个字符的字符串
字符串不必都是相同的长度
<?php
header('Content-Type: text/plain;; charset=utf-8');
//$numbers = array(38001, 38002, 38003);
//$numbers = array(38001, 38002, 38010);
$numbers = array('f38001','f38102','f38100');
$len = 999;
$match = array();
$match = str_split($numbers[0]);
foreach($numbers as $key=>$value){
$chars = str_split($value);
$result = array();
foreach($chars as $ndx=>$char){
$result[$ndx] = $char;
if($char != $match[$ndx]){
if($len > $ndx){$len=$ndx;}
$result = array_slice($result, 0, $len);
break;
}
}
}
$answer = join($result);
echo "\na=$answer";
?>
答案 1 :(得分:0)
尝试一下
<?php
$num=array();
$num=str_split(38002);
$num=str_split("f38001");
$temp=array();
echo match($num, 3)."<br>";
echo match($num, 2)."<br>";
echo match($num, 2)."<br>";
function match ($num,$match){
foreach ($num as $key => $value) {
echo $value."";
if (($key==$match)and ($value !== 0)){
break;
}
}
}
?>