5

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.

1

1 Answer 1

4

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.