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

PHP实现获取包含指定标签的内容并删除原字符串对应部分

解决方案

1. 修改函数以获取包含标签的完整片段

原函数仅截取标签间的文本,我们调整截取逻辑,让它包含起始和结束标签本身:

function get_string_with_tags($string, $start, $end) {
    $startPos = strpos($string, $start);
    // 检查起始标签是否存在
    if ($startPos === false) {
        return '';
    }
    // 从起始标签之后查找结束标签的位置
    $endPos = strpos($string, $end, $startPos + strlen($start));
    // 检查结束标签是否存在
    if ($endPos === false) {
        return '';
    }
    // 截取从起始标签开始到结束标签结束的完整片段
    return substr($string, $startPos, $endPos - $startPos + strlen($end));
}

2. 获取目标片段并更新原字符串

使用上述函数获取包含标签的内容,再通过str_replace删除原字符串中的该片段:

// 原字符串
$str = 'This is the content total <div class="brown">This content brown</div> and this another content <div class="red">This is content brown</div> and this finish.';
$startTag = '<div class="brown">';
$endTag = '</div>';

// 获取包含标签的目标片段
$find = get_string_with_tags($str, $startTag, $endTag);

// 从原字符串中删除该片段
$str = str_replace($find, '', $str);

执行后,$find的值就是你需要的<div class="brown">This content brown</div>,$str也会更新为删除后的目标字符串。

3. 处理多个匹配的情况

如果原字符串中有多个符合条件的<div class="brown">标签,可使用正则表达式批量获取和删除:

// 获取所有匹配的完整片段
preg_match_all('/' . preg_quote($startTag, '/') . '(.*?)' . preg_quote($endTag, '/') . '/s', $str, $matches);
$allFinds = $matches[0]; // 所有包含标签的片段数组

// 删除所有匹配的片段
$str = preg_replace('/' . preg_quote($startTag, '/') . '(.*?)' . preg_quote($endTag, '/') . '/s', '', $str);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:01:01