我正在与Laravel一起开发一种页面生成器,并try 实现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
]
]
如何排除字符串中的空格EXPLAGE?