用PHP替换文件中的数组键值

时间:2017-06-26 06:40:36

标签: php

我想编辑数组php文件中的值。

this is lang.php    
$lang = array (
    'l_name' => "Language",
    'b' => "Break");

我想将'l_name' => "Language",替换为'l_name' => "Hi its me.",

我该怎么做?

$fileContents = file_get_contents($path_to_file);
$search = array('l_name');
$replace = array('Hi, its me');
$newContents = str_replace($search, $replace, $fileContents);
$handle = fopen($path_to_file ,"w");
fwrite($handle, $newContents);
fclose($handle);

我试过这个,但它没有用它取代键'l_name'

我想替换key的值,我该怎么做?

提前致谢。

2 个答案:

答案 0 :(得分:1)

检查以下代码并相应更换。

<?php

//Replace 'l_name' key value:
echo "\n\nReplace 'l_name' key value: \n";
$lang = array (
    'l_name' => "Language",
    'b' => "Break");
$search = $lang['l_name'];
$replace = 'Hi, its me';
$newContents = str_replace($search, $replace, $lang);
print_r($newContents);

//Replace all key value
$newArr = array();
foreach($lang as $key=>$val)
{
  $newArr[$key] = 'Hi, its me';
}

echo "\n\nReplace all key value: \n";
print_r($newArr);

<强>输出

Replace 'l_name' key value: 
Array
(
    [l_name] => Hi, its me
    [b] => Break
)


Replace all key value: 
Array
(
    [l_name] => Hi, its me
    [b] => Hi, its me
)

演示:Click Here

答案 1 :(得分:0)

问题是,如果在代码中使用字符串,则必须做出一些假设。只要间距正确并且您坚持使用相同类型的引号,以下内容将起作用...

$fileContents = file_get_contents("t1.php");
$search = '\'l_name\' => "Language"';
$replace = '\'l_name\' => "Hi, its me"';
$newContents = str_replace($search, $replace, $fileContents);
$handle = fopen("t1.php","w");
fwrite($handle, $newContents);
fclose($handle);

您可以使用AST解析器(https://github.com/nikic/php-ast),这将允许您以更可靠的方式更改代码,但它们更复杂。