用于在PHP中解析注释变量的正则表达式

用于在PHP中解析注释变量的正则表达式

问题描述:

I have a comment block that can look like this;

/**
 * variable1: value
 * variable2: value
 */

or like this;

/*
variable1: value
variable2: value
*/

What I need is to be able to match any number of variable/value pairs and add them to an array. I can't seem to figure it out though, I keep matching the wrong things.

All variables would be single-line, so that should simplify things a little. Spaces before 'variable' or after the the colon should be disregarded, but any other spaces in the value lines should be retained.

UPDATE:

What I ended up going with was a slight expansion of the selected answer;

/(\w)*\s*:\s*([\w'"\/.: ]*)/

It allowed for URLs to be used as values like so;

/**
 * url: 'some/file.png'
 * url: "http://www.google.ca/intl/en_ca/images/logo.gif"
 */

我有一个注释块,看起来像这样; p>

  / ** 
 * variable1:value 
 * variable2:value 
 * / 
  code>  pre> 
 
 

或者像这样; p> / * variable1:value variable2:value * / code> pre>

我需要的是能够匹配任意数量的变量/ 值对并将它们添加到数组中。 我似乎无法解决这个问题,但我一直在纠正错误。 p>

所有变量都是单行的,所以这应该简化一些事情。 应忽略“变量”之前或冒号之后的空格,但应保留值行中的任何其他空格。 p>

更新: p>

我最终得到的是所选答案的轻微扩展; p>

  /(\ w)* \ s *:\ s *([\ w'“\ /  。:] *)/ 
  code>  pre> 
 
 

它允许将URL用作类似的值; p>

  /  ** 
 * url:'some / file.png'
 * url:“http://www.google.ca/intl/en_ca/images/logo.gif"
 * / 
  code>   pre> 
  div>

Does this not work? (Assuming multi-line matching enabled)

(\w)*\s*:\s*(\w*)

I assume you pulled off the comment block with something like

\/\*.*?\*\/

with . set to match anything.

you can try this:

$str=<<<A
/**
 * variable1: value
 * variable2: value
 */

some text

/*
variable1: value
variable2: value
*/

A;

preg_match("/\/\*(.*?)\*\//sm",$str,$matches);
foreach($matches as $k=>$v){
    $v = preg_replace("/\/|\*/sm","",$v);
    $v = array_filter(explode("
",$v));
    print_r($v);
}

output

$ php test.php
Array
(
    [1] =>   variable1: value
    [2] =>   variable2: value
    [3] =>
)
Array
(
    [1] => variable1: value
    [2] => variable2: value
)

now you can separate those variables using explode etc..