PHP将字符串中每个第一个字符的位置放入数组中

Tri*_*e C 6 php regex position

给定一个字符串,例如:

$string = "  this     is   a   string  ";
Run Code Online (Sandbox Code Playgroud)

返回包含一个数字的csv数组的最佳方法是什么,每个单词代表其第一个字符位置,如下所示:

$string = "  this     is   a   string  ";
             ^        ^    ^   ^
             2        11   16  20
Run Code Online (Sandbox Code Playgroud)

理想情况下,输出只是一个数组:

2,11,16,20
Run Code Online (Sandbox Code Playgroud)

到目前为止,这就是我所拥有的,但我认为鉴于我的技能有限,这有点过头了:

$string = "  this     is   a   string  ";
$string = rtrim($string); //just trim the right sides spaces
$len = strlen($string);
$is_prev_white = true;
$result = "";
for( $i = 0; $i <= $len; $i++ ) {
    $char = substr( $string,$i,1);
    if(!preg_match("/\s/", $char) AND $prev_white){
        $result .= $i.",";
        $prev_white = false;
    }else{
        $prev_white = true;
    }   
}
echo $result;
Run Code Online (Sandbox Code Playgroud)

我得到:2,4,11,16,20,22,24,26

Rom*_*est 2

简单,但渐进:) 和preg_match_all函数的解决方案array_walk: 使用preg_match_all带有标志的函数PREG_OFFSET_CAPTURE

PREG_OFFSET_CAPTURE:如果传递此标志,则对于每个发生的匹配,还将返回附加字符串偏移量。请注意,这会将matches的值更改为一个数组,其中每个元素都是一个数组,由偏移量 0 处的匹配字符串及其在偏移量 1 处的主题中的字符串偏移量组成。

$string = "  this     is   a   string  ";   // subject
preg_match_all("/\b\w+\b/iu", $string, $matches, PREG_OFFSET_CAPTURE);

array_walk($matches[0], function(&$v){   // filter string offsets
    $v = $v[1];
});
var_dump($matches[0]);

// the output:
array (size=4)
  0 => int 2
  1 => int 11
  2 => int 16
  3 => int 20
Run Code Online (Sandbox Code Playgroud)

http://php.net/manual/en/function.preg-match-all.php

http://php.net/manual/en/function.array-walk.php