2017-10-13 60 views
1

从文件替换文本我想多维数组中搜索和.txt文件查找和使用多维数组PHP

$array = [[0] => Array (
     [Advertisement and Printing] => 6 
     ) 
    [1] => Array (
     [Advertising Agencies] => 7 
     ) 
    [2] => Array (
     [Advertising Materials] => 8 
     ) 
    [3] => Array (
     [Airport Ads] => 9 
     )] 
    ... 

等替换文本的价值...

.txt文件内容

Advertisement and Printing -> Advertising Materials 
Health Care -> Medical Laboratory 
Business Services -> ISO Consultants 
Packaging -> Bindings and Laminations 

在上述例子中,以我想替换数组值的字符串,例如 广告和Printi纳克 - >广告材料6 - > 8

$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); 
+0

发布最终预期结果 – RomanPerekhrest

+0

任何尝试???? – AbraCadaver

回答

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 
+0

感谢它解决了我的问题的50%,但它并没有改变价值的文本,例如,如果我在数组[['Business Services'=> 4],['Chartered Accountants'=> 267]]我是得到的输出为4 - >特许会计师,它不会将特许会计师更改为267 – sam

+0

@sam,不会,在您当前的输入下它可以100%地工作。检查你的文本,看看' - >'是否有多个空格。我想,在你的文本中的问题 – RomanPerekhrest