You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何在文件的双引号内写入指定内容?

问题:如何在PHP字符串的双引号内追加内容

现有一段PHP代码:

$tab ="
<th>Waste Collected</th>
<th>2010</th>
<th>2011</th>
<th>2012</th>
<th>2013</th>
<th>2014</th>
<th>2015</th>";

希望在上述代码的双引号内写入<th>2016</th>,但当前使用以下代码会将内容写到双引号外:

$myfile = fopen("table_call.php", "a") or die("Unable to open file!");
$tb = '<th>2016</th>';
fwrite($myfile, $tb);

fclose($myfile);

想要实现的效果是:

$tab ="
    <th>Waste Collected</th>
    <th>2010</th>
    <th>2011</th>
    <th>2012</th>
    <th>2013</th>
    <th>2014</th>
    <th>2015</th>
<th>2016</th>";

请问如何修改代码才能达成需求?


解决方案

直接用a模式追加会把内容写到文件末尾,无法插入到指定的双引号内。正确做法是读取文件内容,定位目标位置后插入新内容,再写回文件:

// 读取目标文件的全部内容
$fileContent = file_get_contents("table_call.php");

// 准备要插入的内容
$newTh = "<th>2016</th>";

// 用正则匹配$tab变量的字符串结构,在双引号闭合前插入新内容
$pattern = '/(\$tab\s*=\s*"[^"]+)(";)/s';
$replacement = '$1' . "\n" . $newTh . '$2';
$updatedContent = preg_replace($pattern, $replacement, $fileContent);

// 将修改后的内容覆盖写入原文件
file_put_contents("table_call.php", $updatedContent);

补充说明:

  • 原代码用fopen("a")是追加到文件最后,自然没法插到字符串的双引号里,必须先读取整个文件内容再修改。
  • 正则表达式的作用是精准定位$tab变量的字符串结尾,把新的<th>插在双引号闭合之前。
  • 如果想要和其他<th>保持一致的缩进,把代码里的"\n" . $newTh改成"\n " . $newTh即可。

内容的提问来源于stack exchange,提问作者Nancy Moore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 11:42:53