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

社交分享插件代码优化:实现使用后删除文本行功能

社交分享插件自动删除已用文本行的代码调整

现有适配社交分享的代码无法实现分享后自动删除file1.txt中已使用的文本行,需调整代码实现以下效果:分享对应链接后,将已用行从file1.txt中移除。

现有代码

$fileNames = 'file1.txt';
$lines = file($fileNames, FILE_IGNORE_NEW_LINES);
$randomLineKey = array_rand($lines);
$randomLine = $lines[$randomLineKey];
unset($lines[$randomLineKey]);
$bom = "http://example.com/".$randomLine;
$get_link = wp_get_link("$bom/".$post_id, $post->post_content);

参考示例

  • 当前分享链接示例:
http://example.com/Lemon
http://example.com/Banana
http://example.com/Apple
  • file1.txt操作前内容:
Lemon
Banana
Apple
  • 预期效果:分享http://example.com/Lemon后,file1.txt内容变为:
Banana
Apple

修改后的代码

$filePath = 'file1.txt';
// 读取文件内容,忽略换行符并跳过空行
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

// 仅当文件有可用内容时执行逻辑
if (!empty($lines)) {
    $randomLineKey = array_rand($lines);
    $randomLine = $lines[$randomLineKey];
    // 移除数组中已使用的行
    unset($lines[$randomLineKey]);
    
    // 生成最终分享链接
    $shareUrl = "http://example.com/{$randomLine}/{$post_id}";
    $get_link = wp_get_link($shareUrl, $post->post_content);
    
    // 将剩余内容写回文件,保留换行格式
    $updatedContent = implode(PHP_EOL, $lines);
    file_put_contents($filePath, $updatedContent);
} else {
    // 文件为空时的 fallback 逻辑
    $get_link = '暂无可用分享链接';
}

关键改动说明

  • 新增FILE_SKIP_EMPTY_LINES参数,读取文件时自动跳过空行,避免无效内容干扰
  • 通过implode(PHP_EOL, $lines)将剩余行拼接成标准换行格式的文本,确保文件结构正常
  • 核心新增file_put_contents()步骤,把修改后的内容写回原文件,实现已用行的物理删除
  • 增加空文件判断,防止数组为空时调用array_rand()报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:06:24