在文本文件中找到一个字符串,然后在该行中添加一些内容

问题描述

|| 我有一个像这样的文本文件:
abc<\\n>
def<\\n>
ghi<\\n>
我想知道如何将某些内容添加到特定行中。输出将类似于:
abc<\\n>
def 123<\\n>
ghi<\\n>
搜索字符串\“ def \”并向该行添加内容。 谢谢     

解决方法

尝试这个:
$file_contents = file_get_contents(\'myfile.txt\');
file_put_contents(\'myfile.txt\',preg_replace(\"/<\\\\n>(.+?)<\\\\n>/\",\"<\\\\n>new text<\\\\n>\",$file_contents)); 
    ,如果您不想成为非常高级的东西,这是一个简单的解决方案: testfile.txt的来源
abc def ghi
abc defghi
abc def ghi
abc dfghi
abc defdef ghi
PHP代码
<?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 />\';
}
?>
输出为:
abc def 123 ghi 
abc def 123ghi 
abc def 123 ghi 
abc dfghi 
abc def 123def 123 ghi
您可能想查看有关文件功能的PHP文档     ,
<?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\' );
?>
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...