我想用外部文件中的 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);
Run Code Online (Sandbox Code Playgroud)
但它不起作用。我怎么能那样做?
有没有更好的方法来做到这一点?
非常感谢。
在您的情况下, preg_replace 返回一个字符串,但您根本不使用返回值。
\n\n要将结果写入同一文件中,请使用
\n\nfile_put_contents($arch, preg_replace($patrones, $sustituciones, $filecontent));\nRun Code Online (Sandbox Code Playgroud)\n\n但由于您只是进行一对一的替换,您可以简单地使用strtr:
\n\n$fileName = \'myfile.txt\';\n$content = file_get_contents($fileName);\n$charMappings = [\n \'\xc3\xa1\' => \'a\',\n \'\xc3\xa0\' => \'a\',\n \'\xc3\xa4\' => \'a\',\n \'\xc3\xa2\' => \'a\',\n];\nfile_put_contents($fileName, strtr($content, $charMappings));\nRun Code Online (Sandbox Code Playgroud)\n