我想在多维数组中搜索并替换.txt文件中文本的值
Advertisement and Printing -> Advertising Materials
Health Care -> Medical Laboratory
Business Services -> ISO Consultants
Packaging -> Bindings and Laminations
依旧......
.txt文件内容
$fileContents = file_get_contents("theFile.txt");
$search = $array;
$replace = array(); // Not sure about the replace
$newContents = str_replace($search, $replace, $fileContents);
$handle = fopen("theFile.txt","w");
fwrite($handle, $newContents);
fclose($handle);
例如,在上面的例子中,我希望用数组值替换字符串
广告和印刷 - >广告材料至 6 - > 8
a,b,c -> a, ab, abc ...
答案 0 :(得分:0)
preg_replace
解决方案:
// sample array (extended)
$arr = [
['Advertisement and Printing' => 6], ['Health Care' => 1],
['Medical Laboratory' => 3], ['Advertising Materials' => 8],
['Business Services' => 4], ['ISO Consultants' => 12],
['Packaging' => 10], ['Bindings and Laminations' => 14]
];
$lines = file_get_contents('theFile.txt');
$result = "";
foreach ($arr as $key => $val) {
list($k, $v) = each($val);
$lines = preg_replace("/(-> )$k|^$k/m", '${1}'.$v, $lines);
}
print_r($lines);
输出(准备保存到文件中):
6 -> 8
1 -> 3
4 -> 12
10 -> 14