的工作,因爲你的輸入數據被很好地格式化您可以創建一個非常簡單的遞歸後裔解析器 - 即使沒有那麼多的遞歸參與其中。或者只是一個簡單的堆棧:
$props = array_filter(array_map('trim', explode("\n", $prop)));
$stack = [$node = $xml = new SimpleXMLElement('<root/>')];
foreach ($props as $str)
{
if ($str === '}') {
array_pop($stack);
$node = end($stack);
continue;
}
if (preg_match('~^(\w+) {$~', $str, $matches)) {
$node = $stack[] = $node->addChild($matches[1]);
continue;
}
if (preg_match('~^(\w+):\s*(.*)$~', $str, $matches)) {
$node->addChild($matches[1], htmlspecialchars($matches[2]));
continue;
}
throw new UnexpectedValueException(sprintf('Unable to parse: "%s"', $str));
}
$xml->asXML('php://output');
你的第二個例子(以前失蹤),然後是(美化)輸出:
<?xml version="1.0"?>
<root>
<button>
<large>
<bond>
<width>10px;</width>
<height>10px;</height>
</bond>
<style>
<background>
<color>#ffffff;</color>
<image>url(www.px.com/aui.png) -10px;</image>
<another>
<width>100px;</width>
<height>100px;</height>
</another>
</background>
</style>
</large>
<small>
<bond>
<width>10px;</width>
<height>10px;</height>
</bond>
<style>
<color>#fff;</color>
<border>1px solid #000;</border>
</style>
</small>
</button>
</root>
我建議你使用XML這裏,因爲它可以代表結構更好比不能有重複鍵的數組。
也可以使用遞歸函數調用而不是堆棧。但是這需要來包裝輸入流中的無倒帶迭代器不會打破(或使用array_shift
,但我不喜歡那麼多):
$parse = function($p, SimpleXMLElement $t) use (&$parse) {
foreach($p as $s) {
if ($s === '}') {
break;
}
if (preg_match('~^([^ ]+) {$~', $s, $m)) {
$p->next();
$parse($p, $t->addChild($m[1]));
continue;
}
if (preg_match('~^([^:]+):\s*(.*)$~', $s, $m)) {
$n = $t->addChild($m[1], htmlspecialchars($m[2]));
continue;
}
}
};
$props = array_filter(array_map('trim', explode("\n", $prop)));
$xml = new SimpleXMLElement('<root/>');
$parse(new NoRewindIterator(new ArrayIterator($props)), $xml);
$xml->asXML('php://output');
格式符合什麼條件?實際上,如果這是CSS,那麼數組不能工作,因爲可能有重複的鍵。 – hakre 2013-04-07 11:44:35
這不適用於CSS。我會將它們用於我的應用程序屬性,如配置等。上面的鍵只是示例。要閱讀我使用'read('config.debugger.debug_mode');'的屬性。我這樣做是爲了簡化財產分配並簡化財產的閱讀。另外'read()'函數可以在任何地方使用,所以我不需要使用$ GLOBALS ['config'];謝謝。 – 2013-04-07 12:34:42
很高興知道,看起來像CSS一樣。當你問這個問題添加這樣的上下文時,這也是一個好主意。例如。你可以使用第一個存在的東西,比如屬性文件或yaml。甚至只是一個數組。至於你的解決方案:請把它從問題轉移到答案。這是正確的方法,解決方案不屬於這個問題。 – hakre 2013-04-07 12:37:11