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

PHP 8.1中strpos()弃用报错求助:发票模块函数修复指导

PHP 8.1 中字符串处理函数的弃用警告修复方案

问题原因

你的三个字符串处理函数(before/after/between)在PHP 8.1触发弃用警告,核心原因有两点:

  1. 参数无类型约束:函数未限制输入参数为字符串,当after()找不到目标分隔符时会默认返回null,这个null被传入before()的$inthat参数后,会传给strpos()要求为字符串的第一个参数,触发弃用提示。
  2. after()逻辑缺陷:原代码用!is_bool(strpos($inthat, $here))判断是否找到分隔符,但strpos()找不到内容时返回false(布尔类型),此时函数无返回值,默认返回null。

修复后的代码

/* Functions: Before */
function before(string $here, string $inthat): string {
    $pos = strpos($inthat, $here);
    // 找不到分隔符时返回原字符串,可根据业务需求调整为空字符串
    return $pos === false ? $inthat : substr($inthat, 0, $pos);
}

/* Functions: After */
function after(string $here, string $inthat): string {
    $pos = strpos($inthat, $here);
    // 找不到分隔符时返回空字符串,可根据业务需求调整为原字符串
    if ($pos === false) {
        return '';
    }
    return substr($inthat, $pos + strlen($here));
}

/* Functions: Between */
function between(string $here, string $that, string $inthat): string {
    return before($that, after($here, $inthat));
}

关键修改说明

  • 添加类型约束:给所有函数的参数和返回值加上string类型声明,从根源避免null传入strpos()。
  • 处理strpos()返回false的场景:
    • before()中找不到分隔符时,直接返回原字符串(或根据业务需求返回空字符串)。
    • after()中找不到分隔符时,明确返回空字符串(或原字符串),避免返回null。
  • 优化判断逻辑:用$pos === false直接判断是否找到分隔符,这是PHP官方推荐的strpos()结果判断方式,比is_bool()更准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:55:24