简体   繁体   中英

Find & Replace text from a file using multidimensional array php

I want to search in the multidimensional array and replace value of the text in a .txt file

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

and so on...

.txt file content

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

in the above example to i want to replace the string with array value, for example Advertisement and Printing -> Advertising Materials to 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);

preg_replace solution:

// 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);

The output (ready to be saved into a file):

6 -> 8
1 -> 3
4 -> 12
10 -> 14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM