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

PHP中无法移除\n\nVerse x\n类特定字符串模式的问题求助

解决方案

1. 正则表达式替换(推荐方案)

直接用preg_replace匹配\n\nVerse \d+\n模式,一次性完成所有符合条件的内容替换,无需循环,简洁高效:

$originalStr = "\n\nVerse 1\nA love of nature I have found,\nIn the eyes of my beloved hound.\nThe sweet smell of the wildflowers,\nAs we explore the bright green bowers.\n\nVerse 2\nWe travel the hills and meadows so free,\nThe warmth of the sun caressing me.";

// 替换所有\n\nVerse 数字\n的模式
$targetStr = preg_replace('/\n\nVerse \d+\n/', "\n", $originalStr);

echo $targetStr;

执行后会直接得到目标结果:

\nA love of nature I have found,\nIn the eyes of my beloved hound.\nThe sweet smell of the wildflowers,\nAs we explore the bright green bowers.\nWe travel the hills and meadows so free,\nThe warmth of the sun caressing me.

2. 错误原因分析与循环实现修正

你使用while循环+strpos时出现的Cannot assign an empty string to a string offset错误,是因为错误地用字符串偏移赋值(比如像数组一样直接写$str[$pos] = '')。PHP中字符串虽可按数组方式访问单个字符,但不能直接给偏移位置赋值为空字符串,需用片段替换类函数处理。

如果一定要用循环实现,正确写法如下:

$originalStr = "\n\nVerse 1\nA love of nature I have found,\nIn the eyes of my beloved hound.\nThe sweet smell of the wildflowers,\nAs we explore the bright green bowers.\n\nVerse 2\nWe travel the hills and meadows so free,\nThe warmth of the sun caressing me.";

$searchPatternStart = "\n\nVerse ";
while(($pos = strpos($originalStr, $searchPatternStart)) !== false) {
    // 定位数字行的结束位置
    $lineEndPos = strpos($originalStr, "\n", $pos + strlen($searchPatternStart));
    if($lineEndPos !== false) {
        // 替换指定区间内容为\n
        $originalStr = substr_replace($originalStr, "\n", $pos, $lineEndPos - $pos);
    } else {
        break;
    }
}

echo $originalStr;

这种写法通过substr_replace处理片段替换,避免了直接修改字符串偏移,不会触发错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:50:16