duanan1228 2010-09-14 04:22
浏览 45
已采纳

使用php,grep和regex来搜索和替换文件中的代码行

I have a php file that can read the contents of other files perfectly and return them as a string.

$contents = $file->read(); // return as string.

i need to be able to search and replace certain lines

lines that begin with $this->Session->setFlash and end with , true)); must be replaced with

lines that begin with $this->Session->setFlash and end with , true), 'default', array('class'=>'flash_failure'));

I have grep in my machine, if that helps.

finally after the contents is changed, i have a function that will write the contents back

$file->write($contents);

I know this helps to find the lines, but I have no idea how to replace.

^.*Session->setFlash.*, true\)\);$
  • 写回答

2条回答 默认 最新

  • doufu6130 2010-09-14 06:29
    关注

    the solution is thus:

    $contents = preg_replace('/^(.*Session->setFlash.*, true\))\);$/m',
                                             "$1, 'default', array('class'=>'flash_failure'));", $contents);
    

    the multiline modifier is key.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器