在 PHP 中判断字符串是否包含子串,优先使用 str_contains(PHP 8+),它是语义最清晰且性能最优的选择。若需兼容旧版本或处理复杂模式,再分别考虑 strpos !== false 和 preg_match。

str_contains 与 strpos 的底层差异
str_contains 是 PHP 8.0 引入的内置函数,专门用于布尔值判断,其内部实现经过高度优化,直接调用 C 语言层面的内存比较例程,避免了类型转换开销。

在 PHP 7 及更早版本中,开发者通常使用 strpos($haystack, $needle) !== false 来实现相同功能。虽然逻辑正确,但 strpos 返回的是整数索引或布尔值 false,这种混合返回值设计容易导致误判(例如将 0 误认为假)。相比之下,str_contains 始终返回布尔值,代码意图更明确。从性能角度看,两者在处理纯 ASCII 字符串时差距极小,但在长文本或高频调用场景下,str_contains 因减少了中间状态检查而略快。对于非 ASCII 字符(如中文),两者均基于字节流匹配,若需支持多字节编码的正确性,应改用 mb_strpos 或确保输入已统一为 UTF-8 字节流。
preg_match 的性能瓶颈与适用场景
将完整程序放在当前目录下命名为 test.php,通过命令行运行 php test.php 即可验证三种方法的执行耗时与结果一致性。

<?php
// 测试数据
$haystack = "Hello World! This is a PHP performance test.";
$needle = "PHP";
// 1. str_contains (PHP 8+)
if (function_exists('str_contains')) {
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
str_contains($haystack, $needle);
}
$time_str_contains = microtime(true) - $start;
echo "str_contains: " . number_format($time_str_contains * 1000, 2) . " ms\n";
}
// 2. strpos
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
strpos($haystack, $needle) !== false;
}
$time_pos = microtime(true) - $start;
echo "strpos: " . number_format($time_pos * 1000, 2) . " ms\n";
// 3. preg_match
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
preg_match('/' . preg_quote($needle, '/') . '/', $haystack);
}
$time_preg = microtime(true) - $start;
echo "preg_match: " . number_format($time_preg * 1000, 2) . " ms\n";
// 边界测试:子串在开头
$haystack_start = "PHP is great";
$needle_start = "PHP";
echo "strpos(0 index): " . (strpos($haystack_start, $needle_start) !== false ? 'true' : 'false') . "\n";
运行程序后,预期输出显示 str_contains 耗时最短,strpos 紧随其后,而 preg_match 因涉及正则引擎初始化与编译,耗时显著更高(通常为前两者的 5-10 倍)。在边界测试中,strpos 正确返回 true,验证了 !== false 判断的有效性。若将 $needle 改为不存在于 $haystack 中的字符串,三者均能正确返回假值,但 preg_match 仍保持较高的固定开销。
以下代码展示了基准测试框架,重点对比三者在常规匹配与边界情况下的表现。
strpos 的 0 索引陷阱与正则回溯风险
当子串位于目标字符串起始位置时,strpos 返回整数 0,若错误使用 == true 或 === true 判断,会导致逻辑失败,必须严格使用 !== false。
preg_match 在处理包含特殊字符且未转义的正则表达式时,可能触发灾难性回溯(Catastrophic Backtracking),导致 CPU 占用飙升甚至服务超时。因此,除非必须进行模式匹配(如忽略大小写、通配符),否则严禁用正则替代简单子串查找。