0

我试过学习这个,但无论出于何种原因,它都不起作用。

我有以下内容:

  • 此处的文字: 5.3 x 6.0 x 40 米
  • 在代码中是:

    <li><b>
    text here:
    </b>
    5.3 x 6.0 x 40 metres 
    </li>
    

    这个 HTML 在一个变量中,我们称之为 $dimensions 我正在尝试5.3 x 6.0 x 40 metres使用 preg_match_all 提取,理想情况下提取尺寸和测量值,但我无法回显结果。尽管匹配的大小为 5,但它每次都说数组转换为字符串错误。有什么想法吗?

    preg_match_all('/\<li\>([0-9]*\.*[0-9]*)x([0-9]*\.*[0-9]*)x([0-9]*\.*[0-9]*)
                 \s*([a-zA-Z]*)\<\/li\>/',$dimensions,$matches,PREG_PATTERN_ORDER);
             echo sizeof($matches);
             echo($matches[0]);
    

    编辑:

    正如下面的答案所建议的那样:有人说使用 var_dump($matches) 来查看数组包含的内容...原来我有 4 个空数组,这就引出了下一个问题。我的 preg_match_all 有什么问题?

    array (size=5)
        0 => 
           array (size=0)
               empty
        1 => 
           array (size=0)
               empty
        2 => 
           array (size=0)
               empty
        3 => 
           array (size=0)
               empty
        4 => 
           array (size=0)
               empty
    
    4

    3 回答 3

    0
    $dimensions = '<li><b>
    text here:
    </b>
    5.3 x 6.0 x 40 metres 
    </li>';
    $t = simplexml_load_string($dimensions);
    echo $t;
    

    它将提取5.3 x 6.0 x 40 米,而不是您的值

    于 2012-08-04T03:31:34.810 回答
    0

    我建议不要首先使用 pregmatch 用于此类目的,而是使用 htmlDOMdocument并使用 XPath 查询节点,将结果限制为文本本身,然后使用 preg_match_all

      $content = "<li>
                       <b>
                          text here:
                      </b>
                       5.3 x 6.0 x 40 metres 
                 </li>";
      $doc = new DOMDocument();
      $doc->loadHTML($content);
      $xp = new DOMXPath($doc);
      foreach($xp->query('/html/body/li/text()') as $child){
             $dimensionText = $child->textContent;
             preg_match_all('!\d+!', $dimensionText, $matches);
             print_r($matches);
      } 
    

    以上将为您提供每个维度的数值

    于 2012-08-04T03:21:44.790 回答
    0

    尝试使用 var_dump 检查数组包含的内容:

    <?php
    $a = array(1, 2, array("a", "b", "c"));
    var_dump($a);
    ?>
    
    于 2012-08-04T03:07:34.930 回答