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

PHP提取指定license标记内容并过滤其他无关标记块求助

问题解决:提取指定License块并移除其他License相关内容

问题场景

通过file_get_contents()获取到如下结构化字符串:

$string = '
        welcome in
    admin panel
    //start>license[version(lite)]
        lite 
    //end>license[version(lite)]
    //start>license[version(professional)]
        professional
    //end>license[version(professional)]
    //start>license[version(enterprise)]
        enterprise
        //start>license[custom(company1)]
            + custom company1
        //end>license[custom(company1)]
        //start>license[custom(company2)]
            + custom company2
        //end>license[custom(company2)]
    //end>license[version(enterprise)]
    version
        1.4.2
';

需要保留非License块内容,仅保留version(professional)块内的内容,最终输出如下:

welcome in
    admin panel
        professional
    version
        1.4.2

现有代码问题

原代码仅针对version(professional)的起止标记做处理,未识别并跳过其他License块,导致无关License内容被保留。

解决方案

修改逻辑,通过两个状态变量区分是否需要跳过当前块、是否需要保留当前块内容:

  • $skipBlock:标记是否处于需要完全跳过的License块内
  • $keepContent:标记是否处于需要保留内容的professional块内

修改后的代码如下:

$lines = explode("\n", $string);
$output = '';
$skipBlock = false;
$keepContent = false;

foreach ($lines as $line) {
    // 处理License块开始标记
    if (strpos($line, '//start>license[') !== false) {
        if (strpos($line, 'version(professional)') !== false) {
            $keepContent = true;
        } else {
            $skipBlock = true;
        }
        continue;
    }

    // 处理License块结束标记
    if (strpos($line, '//end>license[') !== false) {
        if (strpos($line, 'version(professional)') !== false) {
            $keepContent = false;
        } else {
            $skipBlock = false;
        }
        continue;
    }

    // 根据状态决定是否保留当前行
    if (!$skipBlock || $keepContent) {
        $output .= $line . "\n";
    }
}

// 清理末尾多余换行(可选)
$output = rtrim($output, "\n");
echo $output;

逻辑说明

  1. 遇到任意License块开始标记时,判断是否为professional块:
    • 是则开启$keepContent状态,后续行需要保留
    • 否则开启$skipBlock状态,后续行直接跳过
  2. 遇到任意License块结束标记时,对应关闭状态
  3. 仅当不在跳过块内,或处于需要保留的professional块内时,才将当前行加入输出

验证结果

运行上述代码后,输出与预期完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:04:59