如何找到字符串中每个数字的位置?


How can I find the position of each digit in a string?

我有一个字符串,例如:

12abc3def4

如何使用正则表达式获得该字符串中每个单个数字的位置?

预期输出:

Digit: Position
"1": 0
"2": 1
"3": 5
"4": 9
编辑:

所以我被告知找到的位置是不可能的regex。现在我需要找到字符串中的数字,然后查找它们的位置。问题是我正在使用以下正则表达式:

preg_match('/['d*]/', "12abc3def4", $output) 

一个数字可能出现多次,也可能永远不会出现。也有可能字符串中没有任何数字

但是它只给了我第一个数字"1",并且停在那里。

可以使用preg_match_all标记PREG_OFFSET_CAPTURE

$str = "12abc3def4";
if(preg_match_all('/'d/', $str, $out, PREG_OFFSET_CAPTURE)!==false)
  print_r($out[0]);

'd匹配数字[0-9];参见test in eval.

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 0
        )
    [1] => Array
        (
            [0] => 2
            [1] => 1
        )
    [2] => Array
        (
            [0] => 3
            [1] => 5
        )
    [3] => Array
        (
            [0] => 4
            [1] => 9
        )
)

由于您可以像访问数组一样访问字符串,因此只需简单地遍历字符串,如果是数字则打印位置,例如

<?php
    $str = "12abc3def4";
    echo "Digit | Position<br>";
    for($i = 0, $length = strlen($str); $i < $length; $i++) {
        if(is_numeric($str[$i]))
            echo $i . " | " . $str[$i] . "<br>";
    }
?>
输出:

Digit | Position
    0 | 1
    1 | 2
    5 | 3
    9 | 4

您可以使用str_split()将字符串拆分为数组,并使用array_filter()进行过滤。

表示每个字符位置的原始数组下标被保留:

$str = '12abc3def4';
$filtered = array_filter(str_split($str), function($ch) {
    return ctype_digit($ch); // return `true` for `integer` only
});
print_r($filtered);

收益率:

Array
(
    [0] => 1
    [1] => 2
    [5] => 3
    [9] => 4
)

为了更好地反映示例输出,只需输入var_dump(array_flip($filtered));:

Array
(
    [1] => 0
    [2] => 1
    [3] => 5
    [4] => 9
)

希望这对你有帮助