Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP preg_replace in a file?

I want to replace some characters with preg_replace in a external file.

I'm trying the code below:

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

But it's not working. How could I do that?

Is there any better way to do that?

Thanks a lot.

like image 801
Tárraga Avatar asked Oct 18 '22 22:10

Tárraga


1 Answers

In your case, preg_replace returns a string but you don't use the return value at all.

To write the result into the same file use

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

But since you are only making one to one replacements you could simply use strtr:

$fileName = 'myfile.txt';
$content = file_get_contents($fileName);
$charMappings = [
    'á' => 'a',
    'à' => 'a',
    'ä' => 'a',
    'â' => 'a',
];
file_put_contents($fileName, strtr($content, $charMappings));
like image 169
Michael D. Avatar answered Oct 21 '22 16:10

Michael D.