2015-11-06 34 views
2

我想在外部文件中用preg_replace替換一些字符。PHP 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); 

但它不工作。我怎麼能這樣做?

有沒有更好的方法來做到這一點?

非常感謝。

+0

請問此http://計算器。 com/a/3542866/594138爲你工作? –

回答

3

在你的情況,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));