Get more backlinks from regex than parentheses

Well, it’s really hard to explain in English, so I’ll just give an example.

I will have lines in the following format:

key-value;key1-value;key2-...

and I need to extract the data as an array

array('key'=>'value','key1'=>'value1', ... )

I planned to use regexp to achieve (for the most part) this function and wrote this regex:

/^(\w+)-([^-;]+)(?:;(\w+)-([^-;]+))*;?$/

to work with preg_matchand with this code:

for ($l = count($matches),$i = 1;$i<$l;$i+=2) {
    $parameters[$matches[$i]] = $matches[$i+1];
}

However, regexp explicitly returns only 4 backlinks - the first and last key-value pairs of the input string. Is there any way around this? I know that I can use a regular expression only to validate a string and use PHP explodein loops with excellent results, but I'm really wondering if this is possible with regular expressions.

, key-value; .

+1
6

lookahead :

/\G(?=(?:\w++-[^;-]++;?)++$)(\w++)-([^;-]++);?/

(?=(?:\w++-[^;-]++;?)++$) . , , , . ( ) -, \G , .

, lookahead , . , , , , , - .

, preg_match_all() (false). , : -, , .

+2

regex - , .

$string = "key-value;key1-value";
$s = explode(";",$string);
foreach($s as $k){
    $e = explode("-",$k);
    $array[$e[0]]=$e[1];
}
print_r($array);
+2

preg_match_all(). , - :

$matches = $parameters = array();
$input = 'key-value;key1-value1;key2-value2;key123-value123;';

preg_match_all("/(\w+)-([^-;]+)/", $input, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
   $parameters[$match[1]] = $match[2];
}

print_r($parameters);

EDIT:

, , :

if (preg_match("/^((\w+)-([^-;]+);)+$/", $input) > 0) {
    /* do the preg_match_all stuff */
}       

EDIT2:

if (preg_match("/^(\w+-[^-;]+;)*\w+-[^-;]+$/", $input) > 0) {
    /* do the preg_match_all stuff */
}       
+2

. . , limit explode() .

0

:

$samples = array(
    "good" => "key-value;key1-value;key2-value;key5-value;key-value;",
    "bad1" => "key-value-value;key1-value;key2-value;key5-value;key-value;",
    "bad2" => "key;key1-value;key2-value;key5-value;key-value;",
    "bad3" => "k%ey;key1-value;key2-value;key5-value;key-value;"
);

foreach($samples as $name => $value) {
    if (preg_match("/^(\w+-\w+;)+$/", $value)) {
        printf("'%s' matches\n", $name);
    } else {
        printf("'%s' not matches\n", $name);
    }
}
0

, , (^ $) preg_match_all() , preg_match_all() .

0

All Articles