【问题标题】:PHP preg_replace in a file?PHP preg_replace 在文件中?
【发布时间】:2015-11-06 12:24:45
【问题描述】:

我想用 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);

但它不起作用。我怎么能这样做?

有没有更好的方法?

非常感谢。

【问题讨论】:

标签: php preg-replace


【解决方案1】:

在您的情况下, preg_replace 返回一个字符串,但您根本不使用返回值。

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

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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 2013-08-03
    • 1970-01-01
    • 2011-05-21
    相关资源
    最近更新 更多