說明
此正則表達式會從壞分離出的好東西,但是你必須收集所有的捕獲組2倍的值,並且只使用他們,如果第1組是空
^start\{([^}]*)\}.*?^end\{\1\}[\r\n]*|(.*?)[\r\n]*(?=^start\{[^}]*\}|\Z)
![enter image description here](https://i.stack.imgur.com/bElqY.png)
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] =>
)
什麼是風味/工具? – acdcjunior