将a:b分解为a:c php
例如,我有两个文件 file1.txt 和 file2.txt 例如,file1.txt包含以下内容:将a:b分解为a:c php,php,explode,Php,Explode,例如,我有两个文件 file1.txt 和 file2.txt 例如,file1.txt包含以下内容: a:b markus:lanz peter:heinrichs lach:schnell 例如,file2.txt包含file1.txt第二次分解的以下内容 b:c lanz:hallo heinrichs:gruss schnell:langsam 因此,我希望在php中有以下输出: a:c markus:hallo peter:gruss lach:langsam 这怎么可能 先爆炸
a:b
markus:lanz
peter:heinrichs
lach:schnell
例如,file2.txt包含file1.txt第二次分解的以下内容
b:c
lanz:hallo
heinrichs:gruss
schnell:langsam
因此,我希望在php中有以下输出:
a:c
markus:hallo
peter:gruss
lach:langsam
这怎么可能
先爆炸先搜索还是怎么
谢谢
我目前的代码如下:
<?php
$file1 = 'a:b
markus:lanz
peter:heinrichs
lach:schnell';
$file2 = '
lanz:hallo
heinrichs:gruss
b:c
test:notest
schnell:langsam';
$array = explode(":", $file1);
for($i=0; $i < count($array); $i++) {
$array = explode(":", $file1);
$pattan = $array[$i];
$pattern = '=\n'. $pattan .':(.*)\n=sUm';
$result = preg_match($pattern, $file2, $subpattern);
echo "<br>";
echo $array[$i];
$first = $array[$i];
echo "<br>";
}
$pattern = '=\n'. $first .':(.*)\n=sUm';
$result = preg_match($pattern, $file2, $subpattern);
var_dump($subpattern);
?>
我做错了什么?你怎么看:
$file1="a:b
markus:lanz
peter:heinrichs
lach:schnell";
$file2="b:c
lanz:hallo
heinrichs:gruss
schnell:langsam";
$a1 = explode("\n",$file1);
$a2 = explode("\n",$file2);
if(count($a1) != count($a2)) die("files don't match!");
$final=array();
foreach($a1 as $k=>$line){
$l1 = explode(":",$line);
$l2 = explode(":",$a2[$k]);
$final[]=$l1[0].':'.$l2[1];
}
print_r($final);
我将采用以下方法:
// load your two files into arrays using file() and explode each line on ':'
foreach ([1,2] as $n) {
$files[$n] = array_map(function($x){ return explode(':', trim($x));}, file("file$n.txt"));
}
// with file1, fill the output array with 'a' values using 'b' as the key to output
foreach ($files[1] as $ab) {
$output[$ab[1]]['a'] = $ab[0];
}
// with file2, fill the output array with 'c' values, also using 'b' as the key
foreach ($files[2] as $bc) {
$output[$bc[0]]['c'] = $bc[1];
}
// remove any elements that do not have count 2 (i.e. both a and c values)
$output = array_filter($output, function ($x) { return count($x) == 2; });
您似乎在匹配位置,我不确定搜索的重点是什么。如果数据是从实际文件中读取的,那么您应该首先使用文件来获取包含单行的数组。然后循环这些,并在冒号处分解它们。例如a:b到a:c不重要,顺序是如何明显错误的。变量$file1和$file2不包含您描述的内容。例如,当您将$file1分解为:,它将创建如下数组:{a,bmarkus,lanzpeter,heinrichslach,schnell},我认为这不是您预期的结果。@MuntashirAkon,除非您使用file读取文件。