Reputation: 1625
Essentially I want to take this string full of data-* attributes and turn them into an associative array where the * is the key and the value is the value. E.g.
'data-pageid="11" data-start="12" => [pageid=>'11',start=>'12]
So I've got this ugly regex code that looks like
$pattern = '/data-(\w+)=/';
$string = '<strong class="annotate annotateSelected" data-pageid="1242799" data-start="80" data-end="86" data-canon="Season" data-toggle="tooltip" title="Season (SPORTS_OBJECT_EVENT)" data-placement="top" data-type="SPORTS_OBJECT_EVENT"><em>season</em></strong>';
preg_match_all($pattern,$string,$result);
$arr = array();
foreach($result[1] as $item){
$pat = '/data-'.$item.'="(?P<'.$item.'>\w+?)"/';
preg_match($pat, $string, $res);
$arr[$item] = $res[1];
}
echo print_r($arr);
That prints out
Array
(
[pageid] => 1242799
[start] => 80
[end] => 86
[canon] => Season
[toggle] => tooltip
[placement] => top
[type] => SPORTS_OBJECT_EVENT
)
There has to be a better way of doing this. Is there anyway to distill this into 1 regex function or am I stuck doing this.
Upvotes: 1
Views: 728
Reputation: 70732
You can use Named Capturing Groups and then use array_combine()
...
preg_match_all('~data-(?P<name>\w+)="(?P<val>[^"]*)"~', $str, $m);
print_r(array_combine($m['name'], $m['val']));
Output
Array
(
[pageid] => 1242799
[start] => 80
[end] => 86
[canon] => Season
[toggle] => tooltip
[placement] => top
[type] => SPORTS_OBJECT_EVENT
)
Upvotes: 3