Find the line in the text file and add something to this line

I have a text file with something like this:

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

I want to know how I can add something to a specific line. The result will be something like this:

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

Find the line "def" and add something to this line. Thanks you

+1
source share
3 answers

Try the following:

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

If you do not 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:

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

You can check the PHP documentation about the file function

+2
source
<?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
source

All Articles