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

报告相同问题?

悬赏问题

  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析