Reputation: 51
I have a config file with the following content in it;
[settings]
; absolute path to the temp dir. If empty the default system tmp directory will be used
temp_path = ""
; if set to true: detects if the contents are UTF-8 encoded and if not encodes them
; if set to false do nothing
encode_to_UTF8 = "false"
; default document language
language = "en-US"
; default paper size
paper_size = "A4"
[license]
; license code
code = "8cf34efe0b57013668df0dbcdf8c82a9"
I need to replace the key between the code = "*" to something else, how can I do this with preg_replace()? The config file contains more options so I only need to replace the key between
code = "*replace me*"
It should be something like this;
$licenseKey = 'newLicenseKey';
$configFileContent = file_get_contents(configFile.ini);
$configFileContent = preg_replace('/(code = ")(.*)(")/', $licenseKey, $configFileContent);
But this replaces the whole line with only the new licenseKey.
How can i do this?
Upvotes: 4
Views: 344
Reputation: 621
You need something called PCRE Lookaround Assertions, more specifically: positive lookahead (?=suffix)
and lookbehind (?<=prefix)
. This means you can match prefixes and suffixes without capturing them, so they will not be lost during a regex match&replace.
Your code, using those:
$licenseKey = 'newLicenseKey';
$configFileContent = file_get_contents(configFile.ini);
$configFileContent = preg_replace('/(?<=code = ")(.*)(?=")/', $licenseKey, $configFileContent);
Upvotes: 7
Reputation: 76395
Like I said in my comment, I'd tackle this issue by treating the file as what it is an INI file.
I'll assume you want to update the file, so in this example, I'll overwrite it:
$iniData = parse_ini_file('configFile.ini', true);//quote the filename
foreach ($iniData as $section => $params) {
if (isset($params['code'])) {
$params['code'] = $newCode;
$iniData[$section] = $params;//update section
}
}
//write to new file
$lines = [];//array of lines
foreach ($iniData as $section => $params) {
$lines[] = sprintf('[%s]', $section);
foreach ($params as $k => $v) {
$lines[] = sprintf('%s = "%s");
}
}
file_put_contents('configFile.ini', implode(PHP_EOL, $lines));
You can combine both loops quite easily, to simplify the code:
$lines = [];
foreach ($iniData as $section => $params) {
if (isset($params['code'])) {
$params['code'] = $newCode;
}
$lines[] = sprintf('[%s]', $section);
foreach ($params as $k => $v) {
$lines[] = sprintf('%s = "%s");
}
}
Upvotes: 1