masum billah masum billah - 1 year ago 59
PHP Question

How to parse all attributes of tag from string into array using php?

I have a html string like...

<match id="18" srs="ICC Womens World Cup Qualifier, 2010" mchDesc="BANW vs PMGW" mnum="4th Match">


Using php how i can split/decode/parse this string as a accessible object(key value pair) such as....

array(
"id"=>"18",
"srs"=>"ICC Womens World Cup Qualifier, 2010",
"mchDesc"=>"BANW vs PMGW",
"mnum"=>"4th Match"
);


Output:

Array
(
[id] => 18
[srs] => ICC Womens World Cup Qualifier, 2010
[mchDesc] => BANW vs PMGW
[mnum] => 4th Match
)

Answer Source

This Should Work.

(\w+)\=\"([a-zA-Z0-9 ,.\/&%?=]+)\"

Code PHP:

<?php
$re = '/(\w+)\=\"([a-zA-Z0-9 ,.\/&%?=]+)\"/m';
$str = '<match id="18" srs="ICC Womens World Cup Qualifier, 2010" mchDesc="BANW vs PMGW" mnum="4th Match">
';

preg_match_all($re, $str, $matches);

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

print_r($c);

Output:

Array
(
    [id] => 18
    [srs] => ICC Womens World Cup Qualifier, 2017
    [mchDesc] => BANW vs PMGW
    [mnum] => 4th Match, Group B
    [type] => ODI
    [vcity] => Colombo
    [vcountry] => Sri Lanka
    [grnd] => Colombo Cricket Club Ground
    [inngCnt] => 0
    [datapath] => google.com/j2me/1.0/match/2017/
)

Ideone: http://ideone.com/OQ7Ko1

Regex101: https://regex101.com/r/lyMmKF/7

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download