doufubian3479 2012-11-18 13:03
浏览 46
已采纳

替换某个行号的字符串

I have a big piece of text, and i know at what line number a specific piece of string occurs. I need to replace that with something else. But how can i replace a certain string only at a certain line number?

Example text:

1: Lorem ipsum dolor sit amet, [[consectetur]] adipiscing elit. Aliquam 
2: imperdiet dolor ut urna hendrerit tempus in sit amet nibh. Maecenas 
3: est est, imperdiet quis tristique pulvinar, convallis et justo. 
4:
5: Duis nulla lacus, [[aliquet]] at ornare nec, ultricies ac erat. Aliquam 
6: dignissim, tellus et pharetra [[rhoncus]], magna nisi scelerisque urna, in 
7: imperdiet [[metus]] orci id risus. 

In this case, i only want to replace the [[ characters at line 1 and at line 6 with -- (two dashes).

Is there an easy of doing this in PHP?

  • 写回答

1条回答 默认 最新

  • douang4294 2012-11-18 13:13
    关注

    There's no compact way for PHP, but you can read the file line by line and replace the string, where needed:

    $f = fopen('example.txt', 'r');
    for ($i = 1; ($line = fgets($f)) !== false; $i++) {
        if ($i == 1 || $i == 6)
            $line = str_replace('[[', '--', $line);
    
        echo $line;
    }
    
    fclose($f);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部