开发者

Regex for parsing comment variables in PHP

开发者 https://www.devze.com 2022-12-20 00:41 出处:网络
I have a comment block that can look like this; /** * variable1: value * variable2: value */ or like this;

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开发者_Go百科 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"
 */


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("\n",$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..

0

精彩评论

暂无评论...
验证码 换一张
取 消