douzui6173 2015-11-06 04:24
浏览 10
已采纳

PHP preg_replace在一个文件中?

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条回答 默认 最新

  • dongsang6899 2015-11-06 04:54
    关注

    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));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部