strpos() 不适用于负偏移

strpos() not working with negative offset

我有一个奇怪的,可能是一些愚蠢的东西,但我已经为它绞尽脑汁了。

我正在使用 strpos() 查看字符串是否以某个子字符串结尾,方法是根据 PHP 文档使用所述子字符串长度的负偏移量。据推测,它从大海捞针的末端执行搜索 x 个聊天角色。

var_dump($recipient); //debug
if(strpos( $recipient, '_redacted', -9 ) === FALSE) {
   // do stuff
}

它只是抱怨字符串中没有包含偏移量。然而输出是:

string(29) "fullname@company.tld_redacted"

A PHP Error was encountered

Severity: Warning Message: strpos(): Offset not contained in string

可以清楚地看到该字符串比 9 个字符长得多,那么为什么它会抛出该警告?(并且通过扩展返回 FALSE 并且总是不正确地触发我的条件)

在 PHP 7.1 中添加了对负偏移的支持。
您可能 运行 是旧版本。
始终查看 Changelog 部分 the manual page

您可以尝试这样更改 if 语句的逻辑

var_dump($recipient); //debug
if(strpos( $recipient, '_redacted') === strlen($recipient) - 9) {
   // do stuff
}

试一试,告诉我它是否适合你

使用strrpos instead of strpos.