views:

65

answers:

2

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"
 */
+1  A: 

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.

Stefan Kendall
That sort of works. It matches the whole variable line, without splitting out the name and value. Is it possible to split it to key/value pairs in one regex, or would it need another pass? Also the value needs to support spaces, so \w* doesn't work.
Stephen Belanger
A: 

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..

ghostdog74