regex - Replace line in text file using PHP -
i have text file following data:
1_fjd 2_skd 3_fks i want replace part in text file using php. example want this:
find line starts "2_" , replace "2_word", after '2_' being replaced by:'word'. how can in php?
you don't need regex this. try following:
- load file array using
file(), loop through lines - check if string starts
2_ - if does, replace input
$word, concatenate$resultstring - if if doesn't, concatenate
$resultstring - use
file_get_contents(), write result file
code:
$lines = file('file.txt'); $word = 'word'; $result = ''; foreach($lines $line) { if(substr($line, 0, 2) == '2_') { $result .= '2_'.$word."\n"; } else { $result .= $line; } } file_put_contents('file.txt', $result); now, if replace took place, file.txt contain like:
1_fjd 2_word 3_fks
Comments
Post a Comment