Lum*_*991 4 php replace preg-replace
我有一个包含以下内容的配置文件;
[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"
Run Code Online (Sandbox Code Playgroud)
我需要将code ="*"之间的键替换为其他内容,如何使用preg_replace()执行此操作?配置文件包含更多选项,因此我只需要更换之间的密钥
code = "*replace me*"
Run Code Online (Sandbox Code Playgroud)
它应该是这样的;
$licenseKey = 'newLicenseKey';
$configFileContent = file_get_contents(configFile.ini);
$configFileContent = preg_replace('/(code = ")(.*)(")/', $licenseKey, $configFileContent);
Run Code Online (Sandbox Code Playgroud)
但这只用新的licenseKey替换了整行.
我怎样才能做到这一点?
你需要的东西叫做PCRE环视断言,更具体:积极的预测先行(?=suffix)和回顾后(?<=prefix).这意味着你可以匹配的前缀和后缀,而不捕获它们,所以它们不会正则表达式匹配和替换过程中丢失.
你的代码,使用那些:
$licenseKey = 'newLicenseKey';
$configFileContent = file_get_contents(configFile.ini);
$configFileContent = preg_replace('/(?<=code = ")(.*)(?=")/', $licenseKey, $configFileContent);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
209 次 |
| 最近记录: |