描述
此正则表达式将区分好与坏,但是您必须收集所有捕获组 2 的值,并且仅在第 1 组为空时使用它们
^start\{([^}]*)\}.*?^end\{\1\}[\r\n]*|(.*?)[\r\n]*(?=^start\{[^}]*\}|\Z)
PHP 代码示例:
示例文本
start{outer1}
Recipe A:
start{inner1}
-ingredient1
-ingredient2
end{inner1}
end{outer1}
... something ...
... blah blah blah ...
start{outer2}
Recipe B:
start{inner1}
- ingredient1
end{inner1}
end{outer2}
... something ...
代码
<?php
$sourcestring="your source string";
preg_match_all('/^start\{([^}]*)\}.*?^end\{\1\}[\r\n]*|(.*?)[\r\n]*(?=^start\{[^}]*\}|\Z)/imsx',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>
火柴
请注意,捕获组 2 只有所需的值。
[0] => Array
(
[0] => start{outer1}
Recipe A:
start{inner1}
-ingredient1
-ingredient2
end{inner1}
end{outer1}
[1] => ... something ...
... blah blah blah ...
[2] => start{outer2}
Recipe B:
start{inner1}
- ingredient1
end{inner1}
end{outer2}
[3] => ... something ...
[4] =>
)
[1] => Array
(
[0] => outer1
[1] =>
[2] => outer2
[3] =>
[4] =>
)
[2] => Array
(
[0] =>
[1] => ... something ...
... blah blah blah ...
[2] =>
[3] => ... something ...
[4] =>
)