【问题标题】:php associative arrays, regex, arrayphp关联数组,正则表达式,数组
【发布时间】:2010-08-18 17:03:10
【问题描述】:

我目前有以下代码:

$content = "
<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>";

我需要找到一种方法来创建和排列为name=&gt;value。例如Manufacturer =&gt; John Deere

谁能帮我剪下一个简单的代码我尝试了一些正则表达式,但甚至无法提取名称或值,例如:

$pattern = "/<name>Manufacturer<\/name><value>(.*)<\/value>/";
preg_match_all($pattern, $content, $matches);
$st_selval = $matches[1][0];

【问题讨论】:

    标签: php arrays associative-array


    【解决方案1】:

    您不想为此使用正则表达式。试试SimpleXML

    编辑
    好吧,你为什么不从这个开始:

    <?php
    
    $content = "<root>" . $content . "</root>";
    $xml = new SimpleXMLElement($c);
    print_r($xml);
    
    ?>
    

    编辑 2
    尽管使用正则表达式发布的一些答案可能有效,但您应该养成使用正确工具来完成工作的习惯,而正则表达式不是解析 XML 的正确工具。

    【讨论】:

    • 而且内容似乎不是有效的 xml,所以我遇到了一些错误,例如 SimpleXMLElement::__construct() [simplexmlelement.--construct]: Entity: line 3: parser error : 第 13 行 C:\wamp\www\index.php 文件末尾的额外内容
    • 这看起来不像“真实世界的 xml”,它只是一个标签序列。
    【解决方案2】:

    我正在使用您的 $content 变量:

    $preg1 = preg_match_all('#<name>([^<]+)#', $content, $name_arr);
    $preg2 = preg_match_all('#<value>([^<]+)#', $content, $val_arr);
    $array = array_combine($name_arr[1], $val_arr[1]);
    

    【讨论】:

      【解决方案3】:

      这个比较简单,可以通过正则表达式来解决。应该是:

      $name  = '<name>\s*([^<]+)</name>\s*';
      $value = '<value>\s*([^<]+)</value>\s*';
      
      $pattern = "|$name $value|";
      preg_match_all($pattern, $content, $matches);
      
      # create hash
      $stuff = array_combine($matches[1], $matches[2]);
      
      # display
      var_dump($stuff);
      

      问候

      rbo

      【讨论】:

        【解决方案4】:

        首先,永远不要使用regex to parse xml...

        您可以使用 XPATH 查询来做到这一点...

        首先,将内容包装在根标签中以使解析器满意(如果还没有的话):

        $content = '<root>' . $content . '</root>';
        

        然后,加载文档

        $dom = new DomDocument();
        $dom->loadXml($content);
        

        然后,初始化 XPATH

        $xpath = new DomXpath($dom);
        

        写下你的查询:

        $xpathQuery = '//name[text()="Manufacturer"]/follwing-sibling::value/text()';
        

        然后,执行它:

        $manufacturer = $xpath->evaluate($xpathQuery);
        

        如果我做对了 xpath,它 $manufacturer 应该是 John Deere...

        您可以在 DomXpathbasic primer on XPatha bunch of XPath examples 上查看文档...

        编辑:这行不通(PHP 不支持该语法(following-sibling)。您可以这样做而不是 xpath 查询:

        $xpathQuery = '//name[text()="Manufacturer"]';
        $elements = $xpath->query($xpathQuery);
        $manufacturer = $elements->item(0)->nextSibling->nodeValue;
        

        【讨论】:

        • 文章其实说简单字符串用正则就可以了。
        • 不幸的是它不起作用,它说警告:domdocument::domdocument() 需要至少 1 个参数,0 在第 7 行的 C:\wamp\www\index.php 中给出 致命错误:调用未定义第 8 行 C:\wamp\www\index.php 中的 domdocument::loadXml() 方法
        • 您使用的是什么版本的 PHP? 4?不,恕我直言,即使是简单的 xml 字符串也不能使用正则表达式。这就像说可以将goto 用于简单的事情......
        • +1 goto 参考,并指出 REGEX 甚至不能解析简单的 XML。
        【解决方案5】:

        我想这就是你要找的东西:

        <?php
        $content = "<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>";
        $pattern = "(\<name\>(\w*)\<\/name\>\<value\>(\w*)\<\/value\>)";
        preg_match_all($pattern, $content, $matches);
        
        $arr = array();
        
        for ($i=0; $i<count($matches); $i++){
            $arr[$matches[1][$i]] = $matches[2][$i];    
        }
        
        /* This is an example on how to use it */
        echo "Location: " . $arr["Location"] . "<br><br>";
        
        /* This is the array */
        print_r($arr);
        

        ?>

        如果你的数组有很多元素,不要在for循环中使用count()函数,先计算值,然后作为常数使用。

        【讨论】:

          【解决方案6】:

          我将编辑我的 PHP 错误,但这里有一些 PHP(伪)代码可以提供一些指导。

          $pattern = '|<name>([^<]*)</name>\s*<value>([^<]*)</value>|'
          preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);
          for($i = 0; $i < count($matches); $i++) {
              $arr[$matches[$i][1]] = $matches[$i][2];
          }
          

          $arr 是您要存储名称/值对的数组。

          【讨论】:

            【解决方案7】:

            使用XMLReader

            $content = '<name>Manufacturer</name><value>John Deere</value><name>Year</name><value>2001</value><name>Location</name><value>NSW</value><name>Hours</name><value>6320</value>';
            $content = '<content>' . $content . '</content>';
            $output = array();
            
            $reader = new XMLReader();
            $reader->XML($content);
            $currentKey = null;
            $currentValue = null;
            while ($reader->read()) {
                switch ($reader->name) {
                    case 'name':
                        $reader->read();
                        $currentKey = $reader->value;
                        $reader->read();
                        break;
                    case 'value':
                        $reader->read();
                        $currentValue = $reader->value;
                        $reader->read();
                        break;
                }
                if (isset($currentKey) && isset($currentValue)) {
                    $output[$currentKey] = $currentValue;
                    $currentKey = null;
                    $currentValue = null;
                }
            }
            
            print_r($output);
            

            输出是:

            Array
            (
                [Manufacturer] => John Deere
                [Year] => 2001
                [Location] => NSW
                [Hours] => 6320
            )
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2011-04-17
              • 1970-01-01
              • 1970-01-01
              • 2011-05-29
              • 1970-01-01
              • 2016-01-02
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多