使用 strpos() 配合循环可以获取字符串中某个字符的所有位置。通过不断调用 strpos() 并更新搜索起始偏移量,直到返回 false 为止,即可收集所有匹配索引。

如何一次性获取所有匹配位置的数组?
编写一个封装函数 getAllPositions(),接收目标字符串和待查找字符作为参数。该函数内部维护一个偏移量变量,初始为0,在循环中调用 strpos($str, $char, $offset)。如果找到位置,将其加入结果数组,并将偏移量更新为该位置加1以继续向后搜索;如果未找到(返回 false),则终止循环并返回已收集的位置数组。

$str = "banana";
$char = "a";
function getAllPositions($str, $char) {
$positions = array();
$offset = 0;
while (true) {
$pos = strpos($str, $char, $offset);
if ($pos === false) {
break;
}
$positions[] = $pos;
$offset = $pos + 1;
}
return $positions;
}
$result = getAllPositions($str, $char);
print_r($result); // 输出: Array ( [0] => 1 [1] => 3 [2] => 5 )对于输入 "banana" 和字符 "a",预期结果为 [1, 3, 5]。这表示 "a" 分别出现在索引1、3和5处。函数正确识别了所有出现位置,且没有遗漏或重复。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
立即学习“PHP免费学习笔记(深入)”;
如果字符不存在于字符串中会返回什么?
当待查找字符不在目标字符串中时,strpos() 首次调用即返回 false。循环条件判断为真后直接跳出,返回空数组 []。例如,在 "apple" 中查找 "z",结果将是空数组,不会引发错误或异常。

$str = "apple";
$char = "z";
function getAllPositions($str, $char) {
$positions = array();
$offset = 0;
while (true) {
$pos = strpos($str, $char, $offset);
if ($pos === false) {
break;
}
$positions[] = $pos;
$offset = $pos + 1;
}
return $positions;
}
$result = getAllPositions($str, $char);
var_dump($result); // 输出: array(0) { }对于输入 "apple" 和字符 "z",预期结果为空数组 []。验证了当字符不存在时,程序安全退出并返回空集合,符合预期行为。


















