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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With