我正在尝试使用正则表达式将此文本拆分为数组,但我的正则表达式不够强大。
注意:可以有一个或多个{elseif}
行,就像PHP一样
{if 'Fred' == 'Fred'}
Welcome Sir.
{elseif 'Fred' == 'Wilma'}
Welcome Ma'am.
{else}
Welcome, whatever you are.
{/if}
我想要实现的最终数组看起来像这样:
array(
[0] => array(
[0] => if 'Fred' == 'Fred'
[1] => elseif 'Fred' == 'Wilma'
[2] => else
),
[1] => array(
[0] => Welcome Sir.
[1] => Welcome Ma'am.
[2] => Welcome, whatever you are.
)
);
我正在使用这个正则表达式来执行此操作:
preg_match_all("/\{(if|elseif|else|\/if).*\}(.*)\{(elseif|else|\/if).*\}/isU", $section, $matches);
但是输出了这个:
Array
(
[0] => Array
(
[0] => {if 'Fred' == 'Fred'}
Welcome Sir.
{elseif 'Fred' == 'Wilma'}
[1] => {else}
Welcome, whatever you are.
{/if}
)
[1] => Array
(
[0] => if
[1] => else
)
[2] => Array
(
[0] =>
Welcome Sir.
[1] =>
Welcome, whatever you are.
)
[3] => Array
(
[0] => elseif
[1] => /if
)
)
有人可以帮帮我吗?谢谢!
答案 0 :(得分:1)
假设你的if / else事情将在第二个括号({)
之后开始preg_match_all("/(\{(?:if|elseif|else)[^\}]*\})\s*([^{]+)\s+/mi", $section, $matches);
答案 1 :(得分:1)
这似乎给出了您正在寻找的结果:
$str = "{if 'Fred' == 'Fred'}
Welcome Sir.
{elseif 'Fred' == 'Wilma'}
Welcome Ma'am.
{else}
Welcome, whatever you are.
{/if}";
preg_match_all('/{((if|elsif|else).*)}/', $str, $matches_conditionals);
preg_match_all('/}[\n\s]*(.*)\s*{/imU', $str, $matches_contents);
$result = array($matches_conditionals[1], $matches_contents[1]);
print_r($result);