這種情況的基本算法中像下面
- 每一個序列
{ no-braces-here }
,把它放在一個緩衝區中,與一個神奇的數字標識更換其在緩衝區中的位置
- 重複(1)直到找不到更多的序列
- 對於緩衝區中的每個條目 - 如果它包含魔術數字,用緩衝區中的相應字符串替換每個數字。
- 緩衝區就是我們在PHP中尋找
class Parser
{
var $buf = array();
function put_to_buf($x) {
$this->buf[] = $x[0];
return '@' . (count($this->buf) - 1) . '@';
}
function get_from_buf($x) {
return $this->buf[intval($x[1])];
}
function replace_all($re, $str, $callback) {
while(preg_match($re, $str))
$str = preg_replace_callback($re, array($this, $callback), $str);
return $str;
}
function run($text) {
$this->replace_all('~{[^{}]*}~', $text, 'put_to_buf');
foreach($this->buf as &$s)
$s = $this->replace_all('[email protected](\d+)@~', $s, 'get_from_buf');
return $this->buf;
}
}
測試
$p = new Parser;
$a = $p->run("just text { foo and { bar and { baz } and { quux } } hello! } ??");
print_r($a);
結果
Array
(
[0] => { baz }
[1] => { quux }
[2] => { bar and { baz } and { quux } }
[3] => { foo and { bar and { baz } and { quux } } hello! }
)
讓我知道如果您有任何問題1附件。
不,我不知道你的意思。你能舉一個例子來說明結果數組應該是什麼樣子? – 2010-04-16 03:41:32
增加了數組應該看起來像 – David 2010-04-16 03:44:10
這可能不會像人們直覺上想的那樣微不足道。您需要標記輸入。爲此,您需要提供關於輸入語法的更多輸入。例如;標識符的標準是什麼? (換行符,空格,字符等)。請參閱維基百科有關詞彙分析的文章,瞭解爲什麼它不那麼簡單:http://en.wikipedia.org/wiki/Lexical_analysis – 2010-04-16 03:55:17