I have the following string which I need to be bale to extract the parameters from in order to process the next part of the code. I have manage to do this by doing multiple preg_match_all, but it is not very efficient and/or dynamic.
Example strings (the source might contain multiples): <==OBJECTSTART==>type=>sqltable,objectid=>4000001,options=>1|5|2<==OBJECTEND==>
<==OBJECTSTART==>type=>sqltable,objectid=>4000002,options=>3|8|5<==OBJECTEND==>
What I have so far I have go to the following for a regex expression:
/<==OBJECTSTART==>((. ?),)(. ?)<==OBJECTEND==>/
This gives me the information before the first comma but I have tried the usual + and * to give me a repeat iteration but no luck.
ideally I am looking for an array of objects that looks like the following
[0]=>
[type]=sqltable
[objected]=4000001
[options]=1|5|2
[1]=>
[type]=sqltable
[objected]=4000002
[options]=3|8|5
thanks in advance!
This may not be the most elegant way of parsing this, but I think it gets the job done:
$str = <<<EOS
<==OBJECTSTART==>type=>sqltable,objectid=>4000001,options=>1|5|2<==OBJECTEND==>
<==OBJECTSTART==>type=>sqltable,objectid=>4000002,options=>3|8|5<==OBJECTEND==>
EOS;
foreach (explode(PHP_EOL, $str) as $line) {
$line = preg_replace('/<==OBJECTSTART==>(.*)<==OBJECTEND==>/', '\1', $line);
$pairs = explode(',', $line);
$data = array();
foreach ($pairs as $pair) {
list ($key, $value) = explode('=>', $pair);
$data[$key] = $value;
}
$result[] = $data;
}
print_r($result);
Output:
Array
(
[0] => Array
(
[type] => sqltable
[objectid] => 4000001
[options] => 1|5|2
)
[1] => Array
(
[type] => sqltable
[objectid] => 4000002
[options] => 3|8|5
)
)
First extract that is between <==OBJECTSTART==> and <==OBJECTEND==>
$str= substr($str, strlen("<==OBJECTSTART==>"), -1 * strlen("<==OBJECTEND==>"));
Then get all pairs attribute/value
preg_match_all("#([^\=]*)\=>([^\,<]*)#",str,values);
Finally, combines the keys and the values in a array
$result= array_combine( $values[1], $values[2] );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.