PHP preg_replace 在文件中?

PHP preg_replace in a file?

我想用 preg_replace 替换外部文件中的一些字符。

我正在尝试以下代码:

$arch = 'myfile.txt';
$filecontent = file_get_contents($arch);

$patrones = array();
$patrones[0] = '/á/';
$patrones[1] = '/à/';
$patrones[2] = '/ä/';
$patrones[3] = '/â/';

$sustituciones = array();
$sustituciones[0] = 'a';
$sustituciones[1] = 'a';
$sustituciones[2] = 'a';
$sustituciones[3] = 'a';

preg_replace($patrones, $sustituciones, $filecontent);

但它不起作用。我该怎么做?

有更好的方法吗?

非常感谢。

在您的例子中,preg_replace return 是一个字符串,但您根本不使用 return 值。

要将结果写入同一个文件,请使用

file_put_contents($arch, preg_replace($patrones, $sustituciones, $filecontent));

但是由于您只是进行一对一的替换,您可以简单地使用 strtr:

$fileName = 'myfile.txt';
$content = file_get_contents($fileName);
$charMappings = [
    'á' => 'a',
    'à' => 'a',
    'ä' => 'a',
    'â' => 'a',
];
file_put_contents($fileName, strtr($content, $charMappings));