I want to edit values in a array php file.
this is lang.php
$lang = array (
'l_name' => "Language",
'b' => "Break");
I want to replace 'l_name' => "Language",
into 'l_name' => "Hi its me.",
how I can do it?
$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);
I tried this but its not working its replacing the key 'l_name'
I want to replace to value of key, How can i do it?
Thanks in advance.
Check below code and replace it accordingly.
<?php
//Replace 'l_name' key value:
echo "
Replace 'l_name' key value:
";
$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 "
Replace all key value:
";
print_r($newArr);
Output
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
)
Demo: Click Here
The problem is that you will have to make some assumptions if your using strings in code. The following will work as long as the spacing is right and you stick to the same types of quotes...
$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);
You can work with AST parsers (https://github.com/nikic/php-ast) which will allow you to change code in a more reliable way, but they are way more complex.