简体   繁体   中英

PHP: data-attributes to associative array using regex

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. Eg

'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.

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
)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM