如何根据php文件中的名称替换.txt文件中的字符串?

问题描述 投票:0回答:1

我有一个包含几个名为.txt的文件的文件夹:

A500_1.txt

A500_2.txt

A700_1.txt

A700_2.txt

A900_1.txt

...

在每个.txt文件中都有:

PRXC1_ | TB | CCAAO9-RC | 9353970324463 | 24.99

PRXC1_ | TB | CFEXK4-RC | 9353970294766 | 84.99

PRXC1_ | TB | CFEXK4-RC | 9353970294773 | 84.99

...

我希望你:

  • 如果文件名以A500_开头,则将“ TB”替换为“ MD”

  • 如果文件名以A700开头,请用“ JB”替换“ TB”

  • 如果文件名以A900开头,请用“ LD”替换“ TB”

你怎么做?

<?php

$oldMessage = 'TB';
$NewMessage = 'MD';

//read the entire string
$str=file_get_contents('./test/A500_1.txt');

//replace something in the file string
$str=str_replace($oldMessage, $NewMessage,$str);

//write the entire string
file_put_contents('./test/A500_1.txt', $str);
echo "good !";

?>
php str-replace
1个回答
0
投票

首先,将文件路径设置为$path = './test/A500_1.txt';之类的变量,然后使用basename提取文件名。现在,您将有一个变量有条件地进行测试。然后考虑一下,由于您将多次执行此操作,因此它应该是易于重用的功能。这应该看起来像这样:

function processFile( $path ) {
    $filename = basename( $path );

    //read the entire string
    $str = file_get_contents( $path );

    //replace something in the file string
    if ( strpos( $filename, 'A500_' ) === 0 ) {
        $str = str_replace( 'TB', 'MD', $str );
    } else if ( strpos( $filename, 'A700_' ) === 0 ) {
        $str = str_replace( 'TB', 'JB', $str );
    } else if ( strpos( $filename, 'A900_' ) === 0 ) {
        $str = str_replace( 'TB', 'LD', $str );
    } else {
        // Return false if we don't know what to do with this file
        return false;
    }

    //write the entire string
    $writeResult = file_put_contents( $path, $str );

    //return true after a file is written successfully, or false on failure
    return $writeResult >= 0;
}

if(processFile( './test/A500_1.txt' )) echo "good!";
© www.soinside.com 2019 - 2024. All rights reserved.