1

いくつかのhtmlエンティティを含む文字列があります

<listing name="name goes there" phone="321321" >Text description</listing>
<anytag name="another name" phone="any phone" attr1="value 1" attr2="value 2">any can be written&nbsp; where &copy;MyRight</anytag>
<anytag name="another name line 2" phone="65851566" attr1="value &euml;" attr2="value 2">any can be written&nbsp; where &reg;MyRight&euml;ous</anytag>

PHPの単一の正規表現でこれらの要素のすべての属性を取得したいのですが、

試しHtmlDomてみるとエラーが発生し、undefined tags使用するSimpleXmlとhtmlエンティティの解析が拒否されます。

だから私はRegExpを試してみましたが、その解決策を見つけることができませんでした。

RegExp以外のソリューションも歓迎します。

4

2 に答える 2

4

次のDOMパーサーベースのコードを使用して、特定のタグ名のすべての属性を一覧表示できます。

$str = <<<EOF
<listing name="name goes there" phone="321321" phone="any phone" attr1="value 1" attr2="value 2">Text description</listing>
<anytag name="another name" phone="any phone" attr1="value 1" attr2="value 2">any can be written&nbsp; where &copy;MyRight</anytag>
<anytag name="another name line 2" phone="65851566" attr1="value &euml;" attr2="value 2">any can be written&nbsp; where &reg;MyRight&euml;ous</anytag>
EOF;
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($str);

$nodeList = $dom->getElementsByTagName('anytag');
for($i=0; $i < $nodeList->length; $i++) {
    $node = $nodeList->item($i);
    if ($node->hasAttributes())
       echo $node->nodeName . " =>\n";
       foreach ($node->attributes as $attr) {
          $name = $attr->nodeName;
          $value = $attr->nodeValue;
          echo "Attribute '$name'='$value'\n";
       }
}

ライブデモ: http: //ideone.com/k8SLhr

于 2013-03-14T08:37:32.897 に答える
-1

これはどう:

<?php
  $str = 'your string here';
  $lines = explode("\n", $str);

  foreach ($lines as $line){
      preg_match_all("@\s+(?<attr_name>)\w+\=\"(?<attr_value>[^\"]+)\"@msi", $line, $results);

      echo "<pre>";
      print_r($results);
      echo "</pre>";
  }

?>
于 2013-03-14T08:42:45.533 に答える