1

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.

0

1 Answer 1

3

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
)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.