如何在字符串中找到一个字符的出现数组

4
我正在寻找一个PHP函数,可以返回字符串中某个字符的位置数组。输入参数"hello world",'o' 将返回 (4,7)。
谢谢。
4个回答

9
无需循环操作。
$str = 'Hello World';
$letter='o';
$letterPositions = array_keys(array_intersect(str_split($str),array($letter)));

var_dump($letterPositions);

+1 很好,必须更加熟练地掌握这些数组函数。 - hakre

2

1
在 PHP 中没有这样的函数存在(据我所知),可以做到你想要的,但是你可以利用 preg_match_all 来获取子字符串模式的偏移量:
$str = "hello world";

$r = preg_match_all('/o/', $str, $matches, PREG_OFFSET_CAPTURE);
foreach($matches[0] as &$match) $match = $match[1];
list($matches) = $matches;
unset($match);

var_dump($matches);

输出:

array(2) {
  [0]=>
  int(4)
  [1]=>
  int(7)
}

演示


0
function searchPositions($text, $needle = ''){
    $positions = array();
    for($i = 0; $i < strlen($text);$i++){
        if($text[$i] == $needle){
            $positions[] = $i;
        }
    }
    return $positions;
}

print_r(searchPositions('Hello world!', 'o'));

好的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接