1

这是一个示例字符串:

“来自 12 人的 60 条评论,20% 的用户” (我们称之为 $v)

我一直在使用 preg_match_all 来获取包含所有数字的数组

$pattern = '!\d+!';
preg_match_all($pattern, $v, $matches, PREG_SET_ORDER); 

我得到的结果是:

Array
(
    [0] => Array
        (
            [0] => 60
        )
    [1] => Array
        (
            [0] => 12
        )
    [2] => Array
        (
            [0] => 20
        )
)

但是尽管尝试了一段时间,我还是没有得到我想要的。我想要的是这样的:

Array
(
    [0] => 60
    [1] => 12
    [2] => 20
)

也许我应该使用 preg_match 代替?但是使用 preg_match 我只能得到一个值......或者也许还有一个循环?它看起来像一个丑陋的黑客......应该有一个专业的出路......提前感谢PHP专家!;)

4

2 回答 2

0

这是你想要的吗?,array_values($array)

于 2012-12-08T03:20:09.217 回答
0

假设格式始终保持不变,您可以执行以下操作:

<?php

    // Input string/line
    $v = "60 reviews from 12 people, 20% of users";

    // Match regex (0-9; min 1 or max unlimited numbers)
    preg_match_all("/[0-9]{1,}/", $v, $matches);

    // Remove/sub key
    $matches = $matches[0];

    // Echo out
    print_r($matches);

?>

这将输出:

 Array ( 
       [0] => 60     // < Access using $matches[0]
       [1] => 12     // < Access using $matches[1]
       [2] => 20     // < Access using $matches[2]
 )
于 2012-12-08T03:36:41.847 回答