如何找到字符串的ID标记并获取其值

时间:2011-05-04 04:27:20

标签: php

由于Drupal Calendar的功能令人困惑,我将不得不做一些不同的事情。

我需要从包含html代码的数组中获取id标记及其值。

<div class="view-item view-item-calendar" id="node-154">
  <div class="calendar.111.field_showtimes_two.0.0 calendar monthview mainstagetheatre-highlight">
              <div class="view-field view-data-node-title node-title">


        <a href="/tca/mainstage/ninetofivemusical">9 to 5: The Musical</a>      </div>  
      </div>    
</div>

这是我需要解析的代码。是否有可能将id标记和我设置的标记作为目标?我这样做是因为我不知道数组的创建位置,所以我可以添加一个节点ID,所以我必须在创建html的地方添加它。

2 个答案:

答案 0 :(得分:0)

您需要一个HTML解析器。不要试图使用正则表达式。

要选择HTML解析器,请参阅此主题Robust and Mature HTML Parser for PHP

答案 1 :(得分:0)

ariel是对的。使用(X)HTML解析器。这应该有效:

$dom = new DOMDocument;
$dom->loadHTML($html_from_above);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//@id') as $node) {
   echo $node->value //found!
}

或者,由于您只有一个id,所以您可能只想使用正则表达式。更好的是,使用strpos / substr。