在system.cfg php中查找并替换值

时间:2018-12-13 18:12:09

标签: php

我有一个小脚本,有了它,我可以转到system.cfg,找到并将值32替换为33。但是,当我没有值32且例如我有值51并想用33代替时该怎么办?如何制作str_replace('code=< anyvalue >','code=33',$file_contents);

<?php
$file = 'system.cfg';
$file_contents = file_get_contents($file);

$fh = fopen($file, "w");
$file_contents = str_replace('code=32','code=33',$file_contents);
fwrite($fh, $file_contents);
fclose($fh);
?>

2 个答案:

答案 0 :(得分:0)

您可以改用preg_replace。您可以找到code=并捕获1个以上的数字。然后在替换中使用code = 32。

$re = '/code=(\d+)/';
$str = 'code=51';
$subst = 'code=32';

$result = preg_replace($re, $subst, $str);

echo $result; // code=32

您还可以在(?<=code=)\d+后面使用正向查找,或者使用code=\K\d+忘记使用\K使用的内容。

然后在替换中使用32而不是code = 32

如果您的匹配不应该是更长匹配的一部分,则可以在正则表达式之前加上单词边界\b

答案 1 :(得分:0)

您应该使用preg_replace而不是str_replace。 preg_replace允许您找到一些字符串/数字模式,并将其替换为其他字符串。但是str_replace仅替换匹配的字符串而不替换模式。

 <?php
    $file = 'system.cfg';
    $file_contents = file_get_contents($file);

    $fh = fopen($file, "w");
    $file_contents = preg_replace('/code=(\d+)/', 'code=33', $file_contents);
    fwrite($fh, $file_contents);
    fclose($fh);
  ?>