Php 仅替换文件格式preg_Replace中的特定组
我有一个包含以下内容的txt文件:Php 仅替换文件格式preg_Replace中的特定组,php,regex,preg-replace,preg-match,Php,Regex,Preg Replace,Preg Match,我有一个包含以下内容的txt文件: fggfhfghfghf $config['website'] = 'Olpa'; asdasdasdasdasdas 以及用于在文件中替换为preg_replace的PHP脚本: write_file('tekst.txt', preg_replace('/\$config\[\'website\'] = \'(.*)\';/', 'aaaaaa', file_get_contents('tekst.txt'))); 但这并不完全符合我的要求 因为
fggfhfghfghf
$config['website'] = 'Olpa';
asdasdasdasdasdas
以及用于在文件中替换为preg_replace的PHP脚本:
write_file('tekst.txt', preg_replace('/\$config\[\'website\'] = \'(.*)\';/', 'aaaaaa', file_get_contents('tekst.txt')));
但这并不完全符合我的要求
因为此脚本将替换整个匹配,并且在更改后,它看起来如下所示:
fggfhfghfghf
aaaaaa
asdasdasdasdasdas
这很糟糕
我只想不改变整个匹配$config['website']='Olpa'代码>但只需更改此Olpa
如你所见,它不属于第2组。匹配信息的类型
我只想改变第二组。一件具体的事情
要最终完成脚本,它将如下所示:
fggfhfghfghf
$config['website'] = 'aaaaaa';
asdasdasdasdasdas
fggfhfghfghf
$config['website'] = 'aaaaaa';
asdasdasdasdasdas
您需要将preg\u replace
更改为
preg_replace('/(\$config\[\'website\'] = \').*?(\';)/', '$1aaaaaa$2', file_get_contents('tekst.txt'))
这意味着,捕获需要保留的内容(然后使用反向引用来恢复文本),并只匹配需要替换的内容
看
图案细节:
(\$config\[\'website\']=\')
-第1组捕获文本$config['website']='
子字符串(稍后用$1
引用)
*?
-除换行符以外的任何0+字符尽可能少
(\”)
-第2组:a,
后接代码>(后面用$2
引用)
如果您的aaa
实际上以一个数字开头,您将需要一个${1}
反向引用。我为您提供了一个更好、更快、更精简的解决方案。不需要捕获组,只需仔细注意转义单引号:
模式:\$config\['website']='\K[^']+
\K
表示“在此处开始完整字符串匹配”,这与否定字符类([^']+
)相结合,可以省略捕获组
(只需25步)
PHP实现:
$txt='fggfhfghfghf
$config[\'website\'] = \'Olpa\';
asdasdasdasdasdas';
print_r(preg_replace('/\$config\[\'website\'\] = \'\K[^\']+/','aaaaaa',$txt));
在模式周围使用单引号是至关重要的,这样就不会将$config
解释为变量。因此,模式中的所有单引号都必须转义
输出: