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

PHP如何匹配指定子串后反向提取strong标签间的子字符串

问题与解决方案

问题背景

我有一段转义后的HTML代码字符串:

$html="
...
euro�<strong>0,00</strong>�sono relativi a Operazioni finanziarie di <strong>Importo Ridotto</strong>;<br/>
                                        euro�<strong>0,00</strong>�sono relativi a Operazioni finanziarie di <strong>Rischio Tripartito</strong>;<br/>
                                        euro�<strong>25.000,00</strong>�sono relativi a Operazioni finanziarie ai sensi del <strong>Dl Liquidita' 08/04/2020 art.13 lettera m)</strong>;<br/>
...";

需求是:当找到指定子串(如Operazioni finanziarie、Rischio Tripartito等)后,从该子串位置反向提取其前方位于<strong>和</strong>之间的值。

初步思路是用strstr($html,$stringToFind,true)获取目标子串之前的内容,再通过带负偏移量的strpos定位目标区间边界,请问该如何实现?

实现方案

按照你的思路,通过反向查找标签边界的方式即可提取目标值,具体实现如下:

分步实现代码

  1. 截取目标子串之前的内容
$stringToFind = "Operazioni finanziarie";
$stringBefore = strstr($html, $stringToFind, true);
  1. 反向查找闭合标签位置
    从截取内容的末尾开始,找到最近的</strong>,作为目标值的右边界:
$closingTagPos = strrpos($stringBefore, '</strong>');
if ($closingTagPos === false) {
    echo "未找到目标闭合标签";
    exit;
}
  1. 反向查找起始标签位置
    从闭合标签的位置往前,找到最近的<strong>,作为目标值的左边界:
$openingTagPos = strrpos(substr($stringBefore, 0, $closingTagPos), '<strong>');
if ($openingTagPos === false) {
    echo "未找到目标起始标签";
    exit;
}
  1. 提取目标值
    计算两个标签之间的内容范围,截取对应值:
$tagLength = strlen('<strong>');
$valueStart = $openingTagPos + $tagLength;
$valueLength = $closingTagPos - $valueStart;
$targetValue = substr($stringBefore, $valueStart, $valueLength);

echo $targetValue; // 示例输出:0,00

封装为可复用函数

如果需要多次查找不同目标子串,可以封装成函数:

function extractStrongValueBefore($html, $stringToFind) {
    $stringBefore = strstr($html, $stringToFind, true);
    if ($stringBefore === false) return false;
    
    $closingTagPos = strrpos($stringBefore, '</strong>');
    if ($closingTagPos === false) return false;
    
    $openingTagPos = strrpos(substr($stringBefore, 0, $closingTagPos), '<strong>');
    if ($openingTagPos === false) return false;
    
    $tagLength = strlen('<strong>');
    $valueStart = $openingTagPos + $tagLength;
    $valueLength = $closingTagPos - $valueStart;
    return substr($stringBefore, $valueStart, $valueLength);
}

// 使用示例
echo extractStrongValueBefore($html, "Operazioni finanziarie"); // 输出 0,00
echo extractStrongValueBefore($html, "Rischio Tripartito"); // 输出 0,00
echo extractStrongValueBefore($html, "Dl Liquidita' 08/04/2020 art.13 lettera m)"); // 输出 25.000,00

注意事项

  • strrpos会取最近的匹配标签,符合“前方紧邻目标子串”的需求;
  • 需处理标签未找到的异常情况,避免程序报错;
  • 要确保转义后的HTML标签拼写完全一致,否则会匹配失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:43:09