Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_replace between string and quotes

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?

like image 369
Lumix1991 Avatar asked Feb 08 '23 18:02

Lumix1991


1 Answers

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);
like image 167
klaar Avatar answered Feb 11 '23 18:02

klaar