Home > database >  preg_match_all combination to get associative array with value inside
preg_match_all combination to get associative array with value inside

Time:03-12

I can't get my head around this. So I need to perse a text in PHP such as this -

mystring = [anything:id="244" boss_fid_name='a' boss_fid_email='b' boss_fid_xyz='test']

And expected array would be -

myarray['boss_fid_name']='a';
myarray['boss_fid_email']='b';
myarray['boss_fid_xyz']='test';

So as you can see the boss_fid_ part is common except for the last part ( there will be more fields just like this and each has the value inside. I was thinking of using explode but then I can't use regex, with pre_replace I can't figure out what would be the proper regex for such a config and then how I would make it an array.

CodePudding user response:

You can to solve this by combination preg_match_all & array_combine functions in next way:

$mystring = "anything:id='244' boss_fid_name='a' boss_fid_email='b' boss_fid_xyz='test'";

preg_match_all("/(\S )='(\S )'/", $mystring, $matches);

$res = array_combine($matches[1], $matches[2]);

Try online preg_match_all & array_combine

Result:

array (
  'anything:id' => '244',
  'boss_fid_name' => 'a',
  'boss_fid_email' => 'b',
  'boss_fid_xyz' => 'test',
)

CodePudding user response:

In my solution, I have replaced the singlequaotes with double quotes. After that I was able to delete the first part with regex and then used the PHP function explode. Then I iterated the new array and assigned it to another result array.

<?php

$str = '[anything:id="244" boss_fid_name="a" boss_fid_email="b" boss_fid_xyz="test"]';

$pattern = '/\[\s?|\]/i';
$o = preg_replace($pattern, '', $str);

$arr = explode(" ",$o);
$res = [];
foreach($arr as $v) {
    $na = explode('=',$v);
    $res[$na[0]] = $na[1];
}
print_r($res);

output

Array
(
    [boss_fid_name] => "a"
    [boss_fid_email] => "b"
    [boss_fid_xyz] => "test"
)
  • Related