doufubian3479 2012-11-18 21: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 21: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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站