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

PHP/WordPress中API返回内容自动转h2、h3标签方案求助

问题描述

我在PHP/WordPress脚本中调用Open API获取标题及文章列表,API返回内容格式如下:

Titles
1. The Versatile Vehicle: Driving with Style
2. Upgrade Your Ride: Discover the Thrills of Automobile Innovation
3. For Travellers and Adventurers: Exploring the Best in Automotive Design
4. Safety on the Road: Navigating with the Latest in Car Technology
5. The Lure of Luxury: Enjoying the Finest in Automotive Comfort

Subtitles
1. Expanding

我希望将其中的Titles项自动转为<h2>标签,Subtitles项转为<h3>标签,示例如下:

<h2>The Versatile Vehicle: Driving with Style</h2>
<h3>Expanding</h3>

我尝试了以下代码但无法正常工作:

$ps = preg_split('#<p([^>])*>#',$txt);

用于将p标签分割为数组;

if (str_contains($ps[1], "Titles")) 
{
    $titles = $ps[2];
}

用于检测字符串是否包含Titles并存储对应内容;

$titles_array = preg_split('#<br([^>])*>#',$titles);

现寻求简单的PHP或JavaScript解决方案。


PHP解决方案

代码实现

<?php
// 假设$api_response是API返回的原始文本
$api_response = "Titles
1. The Versatile Vehicle: Driving with Style
2. Upgrade Your Ride: Discover the Thrills of Automobile Innovation
3. For Travellers and Adventurers: Exploring the Best in Automotive Design
4. Safety on the Road: Navigating with the Latest in Car Technology
5. The Lure of Luxury: Enjoying the Finest in Automotive Comfort

Subtitles
1. Expanding";

// 按换行分割并过滤空行
$lines = array_filter(explode("\n", $api_response), function($line) {
    return trim($line) !== '';
});

$current_tag = '';
$output = '';

foreach ($lines as $line) {
    $trimmed_line = trim($line);
    // 识别区块标记
    if ($trimmed_line === 'Titles') {
        $current_tag = 'h2';
        continue;
    } elseif ($trimmed_line === 'Subtitles') {
        $current_tag = 'h3';
        continue;
    }
    // 提取列表项内容并生成标签
    if (!empty($current_tag) && preg_match('/^\d+\.\s*(.*)$/', $trimmed_line, $matches)) {
        $output .= "<{$current_tag}>" . htmlspecialchars($matches[1]) . "</{$current_tag}>\n";
    }
}

// 输出结果
echo $output;
?>

说明

  1. 先将API返回文本按换行拆分,过滤空行避免无效处理;
  2. 遍历每行内容,识别Titles/Subtitles标记,切换对应的HTML标签类型;
  3. 用正则提取列表项的正文内容,生成对应的标题标签;
  4. 通过htmlspecialchars转义特殊字符,避免XSS风险。

JavaScript解决方案

代码实现

// 假设apiResponse是API返回的原始文本
const apiResponse = `Titles
1. The Versatile Vehicle: Driving with Style
2. Upgrade Your Ride: Discover the Thrills of Automobile Innovation
3. For Travellers and Adventurers: Exploring the Best in Automotive Design
4. Safety on the Road: Navigating with the Latest in Car Technology
5. The Lure of Luxury: Enjoying the Finest in Automotive Comfort

Subtitles
1. Expanding`;

// 拆分文本并过滤空行
const lines = apiResponse.split('\n').filter(line => line.trim() !== '');

let currentTag = '';
let output = '';

lines.forEach(line => {
    const trimmedLine = line.trim();
    // 切换标签类型
    if (trimmedLine === 'Titles') {
        currentTag = 'h2';
        return;
    } else if (trimmedLine === 'Subtitles') {
        currentTag = 'h3';
        return;
    }
    // 提取内容生成标签
    const match = trimmedLine.match(/^\d+\.\s*(.*)$/);
    if (currentTag && match) {
        output += `<${currentTag}>${match[1]}</${currentTag}>\n`;
    }
});

// 输出结果
console.log(output);

说明

  1. 用split('\n')拆分文本,过滤空行;
  2. 遍历行内容,根据标记设置当前要生成的标题标签类型;
  3. 用正则匹配列表项结构,提取正文后拼接成HTML标签;
  4. 最终输出处理后的HTML字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:15:58