在 PHP 中将字符串分解为数组(字符串类似于 WP 短代码)

问题描述 投票:0回答:1

我正在使用 Laravel 开发一种页面构建器,并尝试实现 WordPress 风格的短代码。我有 HTML 代码作为字符串,如下所示:

$string = '<div class="temp">
    [title type="text" tag="h2" value="This is my cool title" disabled some-attribute]
    [text type="text" tag="p" value="Lorem ipsum dolor sit amet"]
</div>';

好吧,现在我想提取所有“短代码”(括号中的内容[...])并将其存储在这样的数组中:

[
  [
   "id" => "title",
   "type" => "text",
   "tag" => "h2",
   "value" => "This is my cool title",
   "disabled" => true,
   "some-attribute" => true
  ],
  [
   "id" => "text",
   "type" => "text",
   "tag" => "p",
   "value" => "Lorem ipsum dolor sit amet"
  ]
]

我的问题是由于“”中的空格而将短代码字符串分解为数组。

这是我的 PHP 代码:

// Extract all brackets from the string
preg_match_all('/(?<=\[)[^\][]*(?=])/', $string, $matches);

$itemsArray = array();
// Explode each shortcode by spaces
foreach ($matches[0] as $match) {
    $shortcode = explode( ' ', $match );
    $itemArray = array();
    // split shortcode in attributes
    foreach ($shortcode as $key => $attr) {
        $temp = explode('=', $attr);
        // First attribute is the id
        if ($key === 0) {
            $itemArray['id'] = $temp[0];
        } else {
            if ( count($temp) > 1 ) {
                $itemArray[ $temp[0] ] = trim($temp[1],'"');
            } else {
                $itemArray[ $temp[0] ] = true;
            }
        }
    }
    $itemsArray[] = $itemArray;
}

结果很接近,但引号“”中的空格搞砸了字符串的爆炸:

[
  [
    "id" => "title"
    "type" => "text"
    "tag" => "h2"
    "value" => "This"
    "is" => true
    "my" => true
    "cool" => true
    "title"" => true
    "disabled" => true
    "some-attribute" => true
  ],
  [
    "id" => "text"
    "type" => "text"
    "tag" => "p"
    "value" => "Lorem"
    "ipsum" => true
    "dolor" => true
    "sit" => true
    "amet"" => true
  ]
]

如何排除字符串爆炸中的空格?

php regex explode
1个回答
0
投票

也许这对你有用?请告诉我

$string = '<div class="temp">
    [title type="text" tag="h2" value="This is my cool title" disabled some-attribute]
    [text type="text" tag="p" value="Lorem ipsum dolor sit amet"]
</div>';

preg_match_all('/\[(\w+)([^]]*)\]/', $string, $matches);

$itemsArray = array();

foreach ($matches[0] as $match) {
    preg_match('/\[(\w+)([^]]*)\]/', $match, $shortcodeMatches);
    $id = $shortcodeMatches[1];
    $attributes = $shortcodeMatches[2];
    
    $itemArray = array();
    $itemArray['id'] = $id;
    
    preg_match_all('/(\w+)=("[^"]*"|\'[^\']*\'|\S+)/', $attributes, $attributeMatches, PREG_SET_ORDER);
    foreach ($attributeMatches as $attrMatch) {
        $key = $attrMatch[1];
        $value = trim($attrMatch[2], '"\'');
        $itemArray[$key] = $value;
    }
    
    $itemsArray[] = $itemArray;
}

print_r($itemsArray);
© www.soinside.com 2019 - 2024. All rights reserved.