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

PHP如何提取换行分隔多文本块中Free与LESSON间的字符串并存入数组

解决方法

实现思路

  • 首先将整段文本按连续换行分割为多个独立的课程块,避免跨行干扰
  • 遍历每个课程块,单独提取Free和LESSON两个标记之间的内容
  • 注意你原有代码的strstr逻辑写反了:strstr($str, $needle, true)返回的是needle之前的内容,要获取Free之后的内容不需要加第三个参数

完整实现代码

<?php

$value = '
Sam Mutimer
3m 8s
Social Media credit
Free
How to find your social media audience
LESSON
How to find your social media audience

Sam Mutimer
3m 20s
Social Media credit
Free
Defining your social media personality
LESSON
Defining your social media personality

Sam Mutimer
2m 5s
Social Media credit
Free
Dealing with complaints on social media
LESSON
Dealing with complaints on social media';

// 按1个以上的连续换行分割为独立块,兼容Windows/Mac/Linux换行符
$blocks = preg_split('/\R{2,}/', trim($value));
$result = [];

foreach ($blocks as $block) {
    // 提取Free之后的内容
    $afterFree = strstr($block, "Free");
    if ($afterFree === false) continue;
    // 去掉Free本身,取后续内容
    $afterFree = substr($afterFree, strlen("Free"));
    // 提取LESSON之前的内容
    $between = strstr($afterFree, "LESSON", true);
    if ($between === false) continue;
    // 去除首尾多余的换行/空格
    $result[] = trim($between);
}

// 输出结果测试
print_r($result);

?>

运行输出

Array
(
    [0] => How to find your social media audience
    [1] => Defining your social media personality
    [2] => Dealing with complaints on social media
)

按单换行拆分的实现方案

如果需要严格按单个换行符先拆分所有行再处理,可以参考如下逻辑:

  1. 用explode("\n", $value)把整个字符串拆分为单行数组
  2. 遍历数组设置标记位:遇到Free后开始收集行内容,遇到LESSON结束收集,将收集到的内容存入结果数组后重置标记位即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 15:36:03