簡體   English   中英

PHP - 將一串 HTML 屬性拆分為一個索引數組

[英]PHP - split a string of HTML attributes into an indexed array

我有一個帶有 HTML 屬性的字符串:

$attribs = ' id= "header " class = "foo   bar" style ="background-color:#fff; color: red; "';

如何將該字符串轉換為索引數組,例如:

array(
  'id' => 'header',
  'class' => array('foo', 'bar'),
  'style' => array(
    'background-color' => '#fff',
    'color' => 'red'
  )
)

所以我可以使用 PHP array_merge_recursive 函數來合並 2 組 HTML 屬性。

謝謝

使用 SimpleXML:

<?php
$attribs = ' id= "header " class = "foo   bar" style ="background-color:#fff; color: red; "';

$x = new SimpleXMLElement("<element $attribs />");

print_r($x);

?>

這假設屬性始終是名稱/值對...

您可以使用正則表達式來提取該信息:

$attribs = ' id= "header " class = "foo   bar" style ="background-color:#fff; color: red; "';
$pattern = '/(\\w+)\s*=\\s*("[^"]*"|\'[^\']*\'|[^"\'\\s>]*)/';
preg_match_all($pattern, $attribs, $matches, PREG_SET_ORDER);
$attrs = array();
foreach ($matches as $match) {
    if (($match[2][0] == '"' || $match[2][0] == "'") && $match[2][0] == $match[2][strlen($match[2])-1]) {
        $match[2] = substr($match[2], 1, -1);
    }
    $name = strtolower($match[1]);
    $value = html_entity_decode($match[2]);
    switch ($name) {
    case 'class':
        $attrs[$name] = preg_split('/\s+/', trim($value));
        break;
    case 'style':
        // parse CSS property declarations
        break;
    default:
        $attrs[$name] = $value;
    }
}
var_dump($attrs);

現在您只需要解析類的class (在空格處拆分)和style屬性聲明(有點難,因為它可以包含帶有;注釋和 URL)。

簡單的方法也可以是:

$atts_array = current((array) new SimpleXMLElement("<element $attribs />"));

您不能使用正則表達式來解析 html 屬性。 這是因為語法是上下文相關的。 您可以使用正則表達式來標記輸入,但您需要一個狀態機來解析它。

如果性能不是什么大問題,最安全的方法可能是將屬性包裝在標簽中,然后通過 html 解析器發送它。 例如。:

function parse_attributes($input) {
  $dom = new DomDocument();
  $dom->loadHtml("<foo " . $input. "/>");
  $attributes = array();
  foreach ($dom->documentElement->attributes as $name => $attr) {
    $attributes[$name] = $node->value;
  }
  return $attributes;
}

您可以通過重用解析器或使用XmlReadersax parser來優化上述內容。

可能這對你有幫助..它做什么..

  • 用 PHP5+ 編寫的 HTML DOM 解析器讓您以非常簡單的方式操作 HTML!
  • 需要 PHP 5+。
  • 支持無效的 HTML。
  • 使用選擇器在 HTML 頁面上查找標簽,就像 jQuery 一樣。
  • 在一行中從 HTML 中提取內容。

http://simplehtmldom.sourceforge.net/

一個簡單有效的函數來解決這個問題

function attrString2Array($attr) {
  $atList = [];

  if (preg_match_all('/\s*(?:([a-z0-9-]+)\s*=\s*"([^"]*)")|(?:\s+([a-z0-9-]+)(?=\s*|>|\s+[a..z0-9]+))/i', $attr, $m)) {
    for ($i = 0; $i < count($m[0]); $i++) {
      if ($m[3][$i])
        $atList[$m[3][$i]] = null;
      else
        $atList[$m[1][$i]] = $m[2][$i];
    }
  }

  return $atList;
}

print_r(attrString2Array('<li data-tpl-classname="class" data-tpl-title="innerHTML" disabled nowrap href="#" hide src = "images/asas.gif">'));
print_r(attrString2Array('data-tpl-classname="class" data-tpl-title="innerHTML" disabled nowrap href="#" hide src = "images/asas.gif"'));

//Array
//(
//    [data-tpl-classname] => class
//    [data-tpl-title] => innerHTML
//    [disabled] => 
//    [nowrap] => 
//    [href] => #
//    [hide] => 
//    [src] => images/asas.gif
//)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM