本文介绍如何在 php 中判断某个子字符串是否出现在数组的任意元素中,而非严格匹配整个数组元素,提供可复用的函数、完整示例及关键注意事项。
在 PHP 开发中,in_array() 只能进行完全相等匹配(即 $string === $array[i]),无法满足“查找子串是否存在于数组某元素内”的需求。例如,给定数组 ["hello", "world", "!"] 和关键词 "wor",我们期望返回 true(因为 "wor" 是 "world" 的子串),但 in_array("wor", $array) 会返回 false。
为此,需手动遍历数组,对每个元素使用 strpos() 进行子串搜索。以下是一个健壮、可复用的封装函数:
function containsSubstringInArray(array $array, string $substring): bool {
foreach ($array as $item) {
if (is_string($item) && strpos($item, $substring) !== false) {
return true;
}
}
return false;
}
// 使用示例
$array = ["hello", "world", "!"];
$string = "wor";
if (containsSubstringInArray($array, $string)) {
echo "match";
} else {
echo "not match"; // 此处不会执行
}✅ 优势说明:
⚠️ 注意事项:
$matches = preg_grep('/\b' . preg_quote($string, '/') . '\b/i', $array);
if (!empty($matches)) { /* 找到完整单词匹配 */ }总结:子串存在性检查不能依赖
in_array(),而应结合 foreach 与 strpos()(或 stripos())手动实现。封装为纯函数不仅提升代码复用性,也增强可读性与可维护性。