【问题标题】:How to parse all attributes of tag from string into array using php?如何使用php将标签的所有属性从字符串解析为数组?
【发布时间】:2017-06-23 20:13:05
【问题描述】:

我有一个类似...的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
)

【问题讨论】:

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


【解决方案1】:

使用DOMDocumentDOMAttr

$str = '<match id="18" srs="ICC Womens World Cup Qualifier, 2010" mchDesc="BANW vs PMGW" mnum="4th Match">';
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($str);

$result = [];

foreach($dom->getElementsByTagName('match')->item(0)->attributes as $attr) {
    $result[$attr->name] = $attr->value;
}

print_r($result);

主要优点是它不关心属性值是用单引号还是双引号括起来(或根本没有引号),等号前后是否有空格。

【讨论】:

    【解决方案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

    正则表达式101:https://regex101.com/r/lyMmKF/7

    【讨论】:

    • 一切正常,但当字符串变为 "google.com/j2me/1.0/match/2017/…">" 那么数据路径无法解析。
    • @masumbillah 已修复。 ^_^ 并添加了对“google.com/j2me/1.0/match/2017/index.php?=potato”和“google.com/j2me/1.0/match/2017/index.php?=potato&?watermelon=”的支持真”
    • 如果模式以\w+开头,则不需要在前面加上单词边界。但是如果你想减少步数,你可以在模式的最开始(括号外)放一个。
    • 但我无法解析 datapath="dhttp://google.com/j2me/1.0/match/2017/2017_ICC_WOMENS_WORLDCUP_QUALIFIER/BANW_PMGW_FEB07/" @Edulynch
    • 我认为 re 应该是 (\w+)\=\"([a-zA-Z0-9 ,._:\/&%?=]+)\" @Edulynch
    猜你喜欢
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    相关资源
    最近更新 更多