我希望得到一些帮助 我认为这将是相当微不足道的 - 如果有点无用,但我显然遗漏了一些东西。
我被赋予了用一串数字识别可能的序列匹配的任务。
我们的想法是获取一串数字,并查看库文件中是否存在任何数字序列
String = 123456789
图书馆= 12,34,56,78,9,123,456,789,1234,56789
我应该生成一个多维匹配数组,
(0)(0 - 12)(1 - 34)(2 - 56)(3 - 78)(4 - 9)
(1)(0 - 123)(1 - 456)(2 - 789)
(2)(0 - 1234)(1 - 56789)
这是我的代码
$library = array('12', '34', '56', '78', '9', '123', '456', '789', '1234', '56789' );
$string = "123456789";
$string = trim(strtolower($string));
echo $string."<hr/>";
function possibles ($library, $string, $c, $array){
$string2 = $string;
$c = 0;
foreach ($library as $sequence){
if(strpos($string2, $sequence) === 0){
$array[$c] = $sequence;
$string2 = substr($string2, strlen($sequence));
echo "-".$sequence."-".$string2."-".$c;
possibles($library, $string2, $c, $array);
} else {$string2 = $string;
echo "*<br/>";
continue;
}
$c++;
$string2=$string;
}
return $array;
}
$array = array();
print_r(possibles($library,$string, $c, $array));
(是的,我尝试格式化)
以上设置为使用找到的内容的回声输出。 1)那些内容不是我所期待的 2)该内容与Print_r
的打印输出不匹配请帮助,因为我看不出我做错了什么:(
[APPEND
这是一个重写版本
$library = array('12', '34', '56', '78', '9', '123', '456', '789', '1234', '56789' );
$string = "123456789";
$string = trim(strtolower($string));
function possibles ($library, $string, $c, $array, $t){
$string2 = $string;
$strlen = strlen($string2);
$c = 0;
foreach ($library as $sequence){
$sequence = trim($sequence);
$sequencelen = strlen($sequence);
if(strpos($string2, $sequence) !== 0 || $strlen < $sequencelen){
break;
}else {
echo $sequence." ";
$array[$c][] = $sequence;
$string2 = substr($string2, strlen($sequence));
possibles ($library, $string2, $c, $array, $t);
}
}$c++;
return $array;
}
$t = array();
$array = array();
print_r(possibles($library,$string, $c, $array, $t));
哪些输出;
数组([0] =&gt;数组([0] =&gt; 12 [1] =&gt; 34 [2] =&gt; 56 [3] =&gt; 78 [4] =&gt; 9))>
这几乎是正确的。序列在那里,但只有第一个
我希望也能看到;
数组([1] =&gt;数组([0] =&gt; 123 [1] =&gt; 456 [2] =&gt; 789))
数组([2] =&gt;数组([0] =&gt; 1234 [1] =&gt; 56789))
在那里,我希望能让它更清晰一点吗?
[APPEND]
考虑一下,还应该有其他序列吗?
12 34 5678 // 1234 56 78 9 // 123 456 78 9等?
答案 0 :(得分:0)
这是一种返回包含所有匹配元素的数组的简单方法:
function getMatches($search, $string) {
$matches = array();
// if it's an array, go through each element and add any matches
if (is_array($search)) {
// let's not consider nested arrays for now
foreach($search AS $s) {
if (strpos($string, $s) !== FALSE) {
$matches[] = $s;
}
}
}
// otherwise we just search right away
elseif (strpos($string, $search) !== FALSE) {
$matches[] = $search;
}
// all matching entries are now in this one-dimensional array
return $matches;
}
根据您的$ library搜索,这将返回一个数组([0] =&gt; 12 [1] =&gt; 34 [2] =&gt; 56,[3] =&gt; 78,[4] = &gt; 9,[5] =&gt; 123,[6] =&gt; 456,[7] =&gt; 789,[8] =&gt; 1234,[9] =&gt; 56789))