计算给定数字之间的差异 "spaces"

Count different "spaces" between a given number

我有一行数字作为字符串:

$numbers = x, 5, 7, x, 9, 4, x, 3, 9, 5, x, ...

现在我要计算x之间的"duration"。

'x'出现:

2x times after [2] numbers
1x times after [3] numbers

我就是想不通,php中的哪种方法最能解决这个问题。

谢谢!

如果数字始终为 0-9,您可以删除逗号和空格并使用 strpos 找出 x 的位置。不需要爆炸。

$numbers = 'x, 5, 7, x, 9, 4, x, 3, 9, 5, x';
$string = str_replace(', ', '', $numbers);

$index = 0;
$previousPosition = 0;
$positionDifferences = array();

while($index < strlen($string)){
    $index = strpos($string, 'x', $index);
    $diff = $index - $previousPosition;
    $positionDifferences[] = $diff;
    $index++;
    $previousPosition = $index;
}

现在 $positionDifferences 将保存一个数组,其中包含 'x' 出现的所有差异。在这个例子中:Array ( [0] => 0 [1] => 2 [2] => 2 [3] => 3 )