如何使用php将字符串的所有属性从字符串解析为数组?

时间:2017-02-06 19:06:46

标签: php regex xml-parsing attributes html-parsing

我有一个像......一样的HTML字符串。

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

使用 php 我如何将此字符串拆分/解码/解析为可访问对象(键值对),例如....

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

输出:

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

2 个答案:

答案 0 :(得分:4)

使用DOMDocumentDOMAttr

inproc://

如果在等号之前或之后有空格,那么如果属性值包含在单引号或双引号之间(或者根本没有引号),那么它的主要优点是它并不在乎。

答案 1 :(得分:2)

这应该有效。

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

代码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);

输出:

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