以下是一些可重复使用的模式。我使用带“x”修饰符的注释来提高可读性。
您还可以编写一个函数,该函数为指定的括号/引号对生成模式。
<?php
$simple_pattern = "( (?#root pattern)
( (?#text or expression)
(?>[^\\(\\)]+) (?#text)
|
\\((?-2)\\) (?#expression and recursion)
)*
)";
$simple_okay_text = "5( 2a + (b - c) ) - a * ( 2b - (c * 3(b - (c + a) ) ) )";
$simple_bad_text = "5( 2)a + (b - c) ) - )a * ( ((2b - (c * 3(b - (c + a) ) ) )";
echo "Simple pattern results:\n";
var_dump(preg_match("/^$simple_pattern\$/x",$simple_okay_text));
var_dump(preg_match("/^$simple_pattern\$/x",$simple_bad_text));
echo "\n----------\n";
$full_pattern = "( (?#root pattern)
( (?#text or expression)
(?>[^\\(\\)\\{\\}\\[\\]<>]+) (?#text not contains brackets)
|
(
[\\(\\{\\[<] (?#start bracket)
(?(?<=\\()(?-3)\\)| (?#if normal)
(?(?<=\\{)(?-3)\\}| (?#if coursed)
(?(?<=\\[)(?-3)\\]| (?#if squared)
(?1)\\> (?#else so if tag)
))) (?#close nested-but-logically-the-some-level subpatterns)
)
)*
)";
$full_okay_text = "5( 2a + [b - c] ) - a * ( 2b - {c * 3<b - (c + a) > } )";
$full_bad_text = "5[ 2a + [b - c} ) - a * ( 2b - [c * 3(b - c + a) ) ) }";
echo "Full pattern results:\n";
var_dump(preg_match("/^$full_pattern\$/x",$simple_okay_text));
var_dump(preg_match("/^$full_pattern\$/x",$full_okay_text));
var_dump(preg_match("/^$full_pattern\$/x",$full_bad_text));
echo "\n----------\n";
$extrafull_pattern = "( (?#root pattern)
( (?#text or expression)
(?>[^\\(\\)\\{\\}\\[\\]<>'\"]+) (?#text not contains brackets and quotes)
|
(
([\\(\\{\\[<'\"]) (?#start bracket)
(?(?<=\\()(?-4)\\)| (?#if normal)
(?(?<=\\{)(?-4)\\}| (?#if coursed)
(?(?<=\\[)(?-4)\\]| (?#if squared)
(?(?<=\\<)(?-4)\\>| (?#if tag)
['\"] (?#else so if static)
)))) (?#close nested-but-logically-the-some-level subpatterns)
)
)*
)";
$extrafull_okay_text = "5( 2a + ['b' - c] ) - a * ( 2b - \"{c * 3<b - (c + a) > }\" )";
$extrafull_bad_text = "5( 2a + ['b' - c] ) - a * ( 2b - \"{c * 3<b - (c + a) > }\" )";
echo "Extra-full pattern results:\n";
var_dump(preg_match("/^$extrafull_pattern\$/x",$simple_okay_text));
var_dump(preg_match("/^$extrafull_pattern\$/x",$full_okay_text));
var_dump(preg_match("/^$extrafull_pattern\$/x",$extrafull_okay_text));
var_dump(preg_match("/^$extrafull_pattern\$/x",$extrafull_bad_text));
?>