Regular expression to reorder string

7

I have the result of a query with several joins , and in a row I have the concatenation of 2 groups. The line returns a string as: 1,4|a1,b4 .

What I need is to regroup ID and Value as follows: array( 1 => a1 , 4 => b4 ) , or similarly, but not wrapped using explode and recombine the array.

I thought about using preg_replace , but I could not get a functional rule.

    
asked by anonymous 20.11.2015 / 01:49

2 answers

7

Alternative version, without RegEx

Not as a response to the main problem, but as an alternative to other users who need to parse of strings in this format, a solution without RegEx follows:

$in   = '1,4|a1,b4';

$pair = explode('|',$in);
$out  = array_combine(explode(',',$pair[0]),explode(',',$pair[1]));

See working at IDEONE .


As posted by bfavaretto ♦ in comments , there is an alternative that rebuilds the data in a single line:

$s='1,4|a1,b4';
$o=call_user_func_array("array_combine", array_chunk(str_word_count($s,1,'1234567890'),2));
print_r( $o );

I have reinstated this alterative because I found it interesting as a showcase of some lesser-known PHP functions. For normal use, explode goes straight to the point.

See working at IDEONE .

    
20.11.2015 / 03:04
0

I believe this expression captures what you want. Just set up the capture groups to extract the data you want.

([1-9][0-9]*,)*[1-9][0-9]*\|[a-z]*(,[a-z]+)*

An important detail is that there is no way, using regular expression, to ensure that the left side has the same amount of items as the right side. This would work for at least one Context Free Grammar .

    
20.11.2015 / 02:23