使用正则表达式的深(无限)分裂单词

时间:2016-03-30 13:36:33

标签: php regex split explode

让我说我有:

$line = "{This is my {sentence|words} I wrote.}"

输出:

This is my sentence I wrote.  
This is my words I wrote.  

但是,正则表达式应匹配深度和嵌套值并拆分这些值,例如:

$line = "{This is my {sentence|words} I wrote on a {sunny|cold} day.}";

输出:

This is my sentence I wrote on a sunny day.  
This is my sentence I wrote on a cold day.  
This is my words I wrote on a sunny day.
This is my words I wrote on a cold day.  

我的第一个虽然是在下面的代码中爆炸,但结果不合适:

$res = explode("|", $line);  

通知书?谢谢。

编辑:这些内容:

$line = "{This is my {sentence|words} I wrote on a {sunny|cold} day.}";
$regex = "{[^{}]*}";
$match = [];

preg_match($regex, $line, $match);

var_dump($match);  

正如已经说过的那样,它可以达到无限,所以没有限制,适合于for循环。

1 个答案:

答案 0 :(得分:3)

检查一下。我通过使用SomeKey替换您的模式并使用vsprintf来完成它,然后以递归方式循环遍历匹配。

我在代码中添加了很多注释......理解递归通常是一个很好的工作。

Here is a working example.

%s

输出:

This is my sentence I wrote on a hot day.
This is my sentence I wrote on a hot night.
This is my sentence I wrote on a cold day.
This is my sentence I wrote on a cold night.
This is my sentence I typed on a hot day.
This is my sentence I typed on a hot night.
This is my sentence I typed on a cold day.
This is my sentence I typed on a cold night.
This is my statement I wrote on a hot day.
This is my statement I wrote on a hot night.
This is my statement I wrote on a cold day.
This is my statement I wrote on a cold night.
This is my statement I typed on a hot day.
This is my statement I typed on a hot night.
This is my statement I typed on a cold day.
This is my statement I typed on a cold night.