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

使用PHP查找字符串中重复变量的第3次出现位置并提取对应内容

解决方案

strpos的第三个参数为搜索偏移量,单次调用默认只会返回第一个匹配项的位置,要定位第N次出现的位置可以通过循环更新偏移量实现,也可以直接用explode拆分字符串简化操作。

方法1:自定义函数定位第N次匹配位置

适用于需要精确获取匹配位置、原字符串体量较大的场景:

/**
 * 查找子串第N次出现后的起始位置
 * @param string $string 原字符串
 * @param string $search 待匹配的子串
 * @param int $n 匹配次数,从1开始计数
 * @return int|false 匹配成功返回第N次子串结束后的偏移位置,失败返回false
 */
function strpos_nth(string $string, string $search, int $n) {
    $search_len = strlen($search);
    $offset = 0;
    for ($i = 1; $i <= $n; $i++) {
        $pos = strpos($string, $search, $offset);
        if ($pos === false) {
            return false;
        }
        $offset = $pos + $search_len;
    }
    return $offset;
}

调用示例:

$origin_str = 't|1t|2t|3t|4';
$target = 't|';
// 获取第3次匹配后的位置
$third_offset = strpos_nth($origin_str, $target, 3);
if ($third_offset !== false) {
    // 提取紧跟的1位数字,需要更长内容可调整substr的第三个参数
    $result = substr($origin_str, $third_offset, 1);
    echo $result; // 输出3
}

方法2:explode拆分字符串(更简便)

如果你的分隔符固定为t|,直接拆分字符串取值效率更高:

$origin_str = 't|1t|2t|3t|4';
$split_arr = explode('t|', $origin_str);
// 拆分后数组为['', '1', '2', '3', '4'],第3次匹配后的内容对应索引3的元素
if (isset($split_arr[3])) {
    // 仅取第一个数字的话访问$split_arr[3][0]即可
    $result = $split_arr[3];
    echo $result; // 输出3
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:27:05