仅替换文件形式的特定组 preg_replace

Replace only specific group in file form preg_replace

我有一个包含内容的 txt 文件:

fggfhfghfghf

$config['website'] = 'Olpa';


asdasdasdasdasdas

和 PHP 脚本,用于替换文件中的 preg_replace:

write_file('tekst.txt', preg_replace('/$config\[\'website\'] = \'(.*)\';/', 'aaaaaa', file_get_contents('tekst.txt')));

但它并没有完全按照我想要的方式工作。

因为这个脚本替换了整个匹配,修改后是这样的:

fggfhfghfghf

aaaaaa


asdasdasdasdasdas

这很糟糕。

我只想不改变整场比赛$config['website'] = 'Olpa';而只是改变这个Olpa

如你所见,它不属于比赛信息的第2组。

我只想改变第 2 组。一件具体的事情。

最终在脚本之后它看起来像:

fggfhfghfghf

$config['website'] = 'aaaaaa';


asdasdasdasdasdas

您需要将 preg_replace 更改为

preg_replace('/($config\[\'website\'] = \').*?(\';)/', 'aaaaaa', file_get_contents('tekst.txt'))

意思是,捕获你需要保留的内容(然后使用反向引用来恢复文本)并匹配你需要替换的内容。

参见regex demo

图案详情:

  • ($config\[\'website\'] = \') - 第 1 组捕获文字 $config['website'] = ' 子字符串(稍后用 </code> 引用)</li> <li><code>.*? - 除换行字符外的任何 0+ 个字符尽可能少
  • (\';) - 第 2 组:' 后跟 ;(后来用 </code> 引用)</li> </ul> <p>如果您的 <code>aaa 实际上以数字开头,您将需要一个 反向引用。

我为您提供了更好、更快、更精简的解决方案。不需要捕获组,只需要注意转义单引号:

模式:$config\['website'] = '\K[^']+

\K 表示 "start the fullstring match here",这与取反字符 class ([^']+) 结合可以省略捕获组。

Pattern Demo(仅需 25 步)

PHP 实施:

$txt='fggfhfghfghf

$config[\'website\'] = \'Olpa\';


asdasdasdasdasdas';
print_r(preg_replace('/$config\[\'website\'\] = \'\K[^\']+/','aaaaaa',$txt));

在模式周围使用单引号至关重要,这样 $config 就不会被解释为变量。因此,模式内的所有单引号都必须转义。

输出:

fggfhfghfghf

$config['website'] = 'aaaaaa';


asdasdasdasdasdas