我有一个包含以下内容的配置文件;
[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"
我需要将代码=" *" 之间的密钥替换为其他内容,如何使用preg_replace()执行此操作?配置文件包含更多选项,因此我只需要替换
之间的密钥code = "*replace me*"
它应该是这样的;
$licenseKey = 'newLicenseKey';
$configFileContent = file_get_contents(configFile.ini);
$configFileContent = preg_replace('/(code = ")(.*)(")/', $licenseKey, $configFileContent);
但是这只用新的licenseKey替换整行。
我该怎么做?
答案 0 :(得分:7)
您需要一些名为PCRE Lookaround Assertions的内容,更具体地说:正向前瞻(?=suffix)
和后瞻(?<=prefix)
。这意味着您可以匹配前缀和后缀而不捕获它们,因此在正则表达式匹配和替换期间它们不会丢失。
您的代码,使用:
$licenseKey = 'newLicenseKey';
$configFileContent = file_get_contents(configFile.ini);
$configFileContent = preg_replace('/(?<=code = ")(.*)(?=")/', $licenseKey, $configFileContent);
答案 1 :(得分:1)
就像我在评论中所说,我通过将文件视为 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");
}
}