如何从字符串中提取多个值来调用数组?

时间:2014-06-29 12:32:17

标签: php regex

我想从字符串中提取值以调用基本模板功能的数组:

$string = '... #these.are.words-I_want.to.extract# ...';

$output = preg_replace_callback('~\#([\w-]+)(\.([\w-]+))*\#~', function($matches) {
    print_r($matches);
    // Replace matches with array value: $these['are']['words-I_want']['to']['extract']
}, $string);

这给了我:

Array
(
    [0] => #these.are.words-I_want.to.extract#
    [1] => these
    [2] => .extract
    [3] => extract
)

但我想:

Array
(
    [0] => #these.are.words-I_want.to.extract#
    [1] => these
    [2] => are
    [3] => words-I_want
    [4] => to
    [5] => extract
)

我需要对正则表达式进行哪些更改?

2 个答案:

答案 0 :(得分:3)

这些单词似乎只是点分开,所以匹配你不想要的序列:

preg_replace_callback('/[^#.]+/', function($match) {
    // ...
}, $str);

应该给出预期的结果。

但是,如果#字符是匹配应该发生的边界,则需要单独匹配,然后在内部使用简单的explode()

preg_replace_callback('/#(.*?)#/', function($match) {
    $parts = explode('.', $match[1]);
    // ...
}, $str);

答案 1 :(得分:3)

您可以使用array_merge()函数合并两个结果数组:

$string = '... #these.are.words-I_want.to.extract# ...';
$result = array();

if (preg_match('~#([^#]+)#~', $string, $m)) {
   $result[] = $m[0];
   $result = array_merge($result, explode('.', $m[1]));
}

print_r($result);

输出:

Array
(
    [0] => #these.are.words-I_want.to.extract#
    [1] => these
    [2] => are
    [3] => words-I_want
    [4] => to
    [5] => extract
)