PHP preg_replace between string and quotation marks

I have a configuration file with the following contents:

[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 = "*" with something else, how can I do this with preg_replace ()? The configuration file contains more parameters, 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 entire string with only the new licenseKey.

How can i do this?

+4
source share
2 answers

-, PCRE Lookaround Assertions, : (?=suffix) lookbehind (?<=prefix). , , .

, :

$licenseKey = 'newLicenseKey';
$configFileContent = file_get_contents(configFile.ini);
$configFileContent = preg_replace('/(?<=code = ")(.*)(?=")/', $licenseKey, $configFileContent);
+7

, , INI.

  • ,
  • - ( )

, , :

$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));

, :

$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");
    }
}
+1

Source: https://habr.com/ru/post/1612420/


All Articles