REGEXP喜欢Smarty,但并不完全如此

时间:2011-09-10 12:59:02

标签: php regex preg-replace

我想创造像smarty这样的东西,但我不想使用Smarty,因为我需要更多JS功能......

我想解析一下:

{{crossLoopStart fromController->messages as message and increment|i every loop}}
wow, this is message number {{message->id}} and text is: {{message->text}}
{{crossLoopEmpty}}
oh no! You haven't any message!
{{crossLoopEnd}}

我做了这个REGEXP:

/\{\{crossLoopStart\s([a-zA-Z0-9>-]+)\s(as\s([a-zA-Z>-]+))?\s?and\s(([a-zA-Z0-9]+\|)?([a-zA-Z0-9]+)\s([a-z]+)\sloop)?\}\}(.+)/

但问题是,当我使用(.+)时(在我的REGEXP的末尾),它会获得所有字符:

wow, this is message number {{message->id}} and text is: {{message->text}}
{{crossLoopEmpty}}
oh no! You haven't any message!
{{crossLoopEnd}}

但我想只得到这个:

wow, this is message number {{message->id}} and text is: {{message->text}}

不是强制性部分:

{{crossLoopEmpty}}
oh no! You haven't any message!

我需要获取所有文字,结束标记符号“crossLoopStart”}} ,并以开头标记字符“crossLoopEmpty”或“crossLoopEnd”结尾 {{

3 个答案:

答案 0 :(得分:2)

我真的不知道你感兴趣的是什么,但以下模式可能会给你所需的部分。

/\{\{crossLoopStart\s([a-zA-Z0-9>-]+)\s(as\s([a-zA-Z>-]+))?\s?and\s(([a-zA-Z0-9]+\|)?([a-zA-Z0-9]+)\s([a-z]+)\sloop)?\}\}(.*?)\{\{crossLoopEmpty\}\}(.*?)\{\{crossLoopEnd\}\}/

使用preg_match可以得到以下结果:

Array
(
    [0] => {{crossLoopStart fromController->messages as message and increment|i every loop}} wow, this is message number {{message->id}} and text is: {{message->text}} {{crossLoopEmpty}} oh no! You haven't any message! {{crossLoopEnd}}
    [1] => fromController->messages
    [2] => as message
    [3] => message
    [4] => increment|i every loop
    [5] => increment|
    [6] => i
    [7] => every
    [8] =>  wow, this is message number {{message->id}} and text is: {{message->text}} 
    [9] =>  oh no! You haven't any message! 
)

答案 1 :(得分:0)

{{crossLoopStart \ S([A-ZA-Z0-9> - ] +)\ S(如\ S([A-ZA-Z> - ] +))?\ S和\ S(( [A-ZA-Z0-9] + \ |?)([A-ZA-Z0-9] +)\ S([AZ] +)\桅)}} [AZ \,\ s]的{1, (?)} \砂[AZ \ s]的{1,} \:(?)\ S {{crossLoopEmpty}} \ S(?*)\ S {{crossLoopEnd}}

使用preg_match(regexp,$ string,$ match);

答案 2 :(得分:0)

如果省略某些参数怎么办?你如何控制你的比赛?我认为你需要使用命名捕获组。

$r = '/(?P<params>(?<={{crossLoopStart)[^\n]*(?=}}$))}}(?P<content>.+(?={{crossLoopEnd}})){{crossLoopEnd}}/ms';
$m = preg_match($r, $t, $matches);
$params = $matches['params'];
$content = $matches['content'];
$empty_content = '';

if (preg_match('/(?P<content>.*){{crossLoopEmpty}}(?P<emptyContent>.*)/ms', $content, $matches)) {
    $content = $matches['content'];
    $empty_content = $matches['emptyContent'];
}
var_dump($params, $content, $empty_content);

通过这种方式,您可以知道您的参数,内容等位于何处。

string(63) " fromController->messages as message and increment|i every loop"
string(76) "
wow, this is message number {{message->id}} and text is: {{message->text}}
"
string(33) "
oh no! You haven't any message!
"

然后以类似的方式解析你的参数。