使用正则表达式解析某个模式

时间:2013-11-19 11:01:25

标签: php regex

这个问题适用于那里的regexperts ......

我有一个文件,其__var:val__字符串遍布各处; 这是一个例子;

__pi:3.14__  blah blah __myname:haluk karamete__ 
some more blah blah __whatever:whatever__ and so on

基本上我正在寻找的模式是“由2个下划线(__)包围的字符串,其中字符串中至少有一个冒号(:)”。这是要求。

最终的目标是编写一个PHP解析器函数,该函数通过这个文档并给我一个关联数组作为结果集,像这样;

array(
   'pi' => '3.14',
   'myname' => 'haluk karamete',
   'whatever' => 'whatever',
);

我在这里寻找什么样的正则表达式?

1 个答案:

答案 0 :(得分:1)

您可以使用preg_match_all

$s = '__pi:3.14__  blah blah __my name:haluk karamete__';
if (preg_match_all('/__([^:]+):([^_]+)__/', $s, $matches)) {
    $output = array_combine ( $matches[1], $matches[2] );
    print_r($output);   
}

输出:

Array
(
    [pi] => 3.14
    [my name] => haluk karamete
)
相关问题