dongtan6543 2016-02-16 18:32
浏览 28
已采纳

在文件中添加一行

So I have this auto-generated HTML file. http://pastebin.com/mTMJNrdm

I'm trying to write a PHP script that replaces line 5 with this.

<LINK href="style.css" rel="stylesheet" type="text/css"></style>

I'm trying to wrap my head around it since it's a file. What function could accomplish this for me?

Current code:

$fh = file('standings.html');

$css = addslashes('<LINK href="style.css" rel="stylesheet" type="text/css"></style>');

$pattern = "</style>";

foreach ($fh as $lines) {
     if (preg_match($pattern, $lines)) {
         // Replace this line with $css
     }
}
  • 写回答

2条回答 默认 最新

  • dongpao2871 2016-02-16 18:46
    关注

    php file function already reads an entire file into an array. Just replace the needed line by specifying the needed index:

    $lines = file('standings.html');
    
    $lines[4] = addslashes('<LINK href="style.css" rel="stylesheet" type="text/css"></style>');
    $new_content = implode(" ", $lines);
    
    file_put_contents('standings.html', $new_content);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试