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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With