这种情况的基本算法中像下面
- 每一个序列
{ 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