Substituir linha em arquivo txt com PHP

Arquivo: ‘file.txt’
1_um
palavra abc
3_tres
4_palavra

<?php
$arquivo = 'file.txt';
$linhas = file( $arquivo );
$string_busca = '^palavra';
$string_substituta = 'substituiu a linha que comecava com palavra por essa';
$conteudo = '';

foreach( $linhas as $linha ) {

  if( eregi( $string_busca, $linha ) ) {
    $conteudo .= $string_substituta . PHP_EOL;
  } else {
    $conteudo .= $linha;
  }
}

file_put_contents( $arquivo, $conteudo );
?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s