使用preg_match或preg_match_all获取具有预定义结构的数组

时间:2012-12-08 03:16:34

标签: php arrays preg-match preg-match-all

以下是一个示例字符串:

“来自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专家! ;)

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分: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]
 )