我有两个文件,例如
file1.txt
和file2.txt
,每个包含两列的行,由一个:
字符分隔。
例如,file1.txt
包含以下内容:(我想使用第一个"列")
a:b
markus:lanz
peter:heinrichs
lach:schnell
并且file2.txt
包含例如以下内容(我想使用第二个"列")
b:c
lanz:hallo
heinrichs:gruss
schnell:langsam
所以我正在寻找以下输出:
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);
?>
使用preg_split
和array_map
函数的解决方案:
$file1_content = "a:b
markus:lanz
peter:heinrichs
lach:schnell";
$file2_content = "b:c
lanz:hallo
heinrichs:gruss
schnell:langsam";
// 'R modifier matches line break among all platforms ('r'n|'n|'r)
$file1_parts = preg_split('/'R/', $file1_content);
$file2_parts = preg_split('/'R/', $file2_content);
$cross_result = array_map(function($fp1, $fp2){
return explode(":", $fp1)[0] .":". explode(":", $fp2)[1] . PHP_EOL;
}, $file1_parts, $file2_parts);
$cross_result = implode("", $cross_result);
print_r($cross_result);
输出:
a:c
markus:hallo
peter:gruss
lach:langsam
$file1 = 'a:b
markus:lanz
peter:heinrichs
lach:schnell';
$array1 = explode("'n", $file1);
$file2 = 'b:c
lanz:hallo
heinrichs:gruss
schnell:langsam';
$array2 = explode("'n", $file2);
$array3 = array();
foreach($array1 as $i => $value) {
$key = explode(':',$value)[0];
$val = explode(':',$array2[$i])[1];
$array3[] = $key.':'.$val;
}
$file3 = implode("'n",$array3);
我的想法/我的代码就像
不工作
但在一些人讨厌或类似的事情之前:
<?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++) {
$pattern = "/^.*'b". $array[$i] ."'b.*$/m";
$matches = array();
preg_match($pattern, $file2, $matches);
var_dump($matches);
echo $array[$i] . ":";
}
?>