开发者

Find a string in a text file and add something to that line

I have a text file with something like this:

abc<\n>
def<\n>
ghi<\n>

I want to know how can I 开发者_开发知识库add something to a specific line.. the output would be something like:

abc<\n>
def 123<\n>
ghi<\n>

Search for string "def" and add something to that line. Thank you


If you don't want to be something very advanced, this is a simple solution:

Source of testfile.txt

abc def ghi
abc defghi
abc def ghi
abc dfghi
abc defdef ghi

PHP Code

<?php
// Get a file into an array.
$lines = file('testfile.txt');

// Loop through our array, show content and replace whatever is needed.
foreach ($lines as $line) {
    $SearchAndReplace=str_replace('def', 'def 123', $line);
    echo $SearchAndReplace.'<br />';
}
?>

Output is:

abc def 123 ghi 
abc def 123ghi 
abc def 123 ghi 
abc dfghi 
abc def 123def 123 ghi

You may wanna check the PHP documentation about file function


Try this:

$file_contents = file_get_contents('myfile.txt');
file_put_contents('myfile.txt', 
     preg_replace("/<\\n>(.+?)<\\n>/", "<\\n>new text<\\n>", $file_contents)); 


<?PHP
function add_to_line( $file_src , $search_word , $new_text )
{
    $file = file( $file_src );
    for( $i = 0 ; $i < count( $file ) ; $i++ )
    {
        if( strstr( $file[$i] , $search_word ) )
        {
            $file[$i] = $file[$i] . $new_text;
            break;
        }
    }
    return implode( "\n" , $file );
}

echo add_to_line( 'sample.txt' , 'def' , '123' );
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜