[英]Match same pattern multiple times
我有一個具有以下結構的字符串:
~ foo;
text 1
~ foo;
text 2
~ foo;
...
~ foo;
text n
~ foo;
我正在嘗試將text 1, text 2 .. text n
放入數組,但是我不知道該怎么做,所以我的問題是: 如何將這些信息放入數組?
我嘗試了以下正則表達式: !~\\s*([a-z0-9 ]+)\\s*(;|\\r|\\r\\n)([^~]*)~\\s*\\\\1!i
,但似乎只匹配第一次出現。 (我試過preg_match_all )
**更新:示例:**
我的弦:
// .. text before... //
~ Key;
some random text
~ Key;
another random text
~ Key;
// .. some random text .. //
~ Key2; some random text again
~ Key2;
another some random text again
~ Key2;
輸出應為:
Array
(
[Key] => Array
(
[0] => some random text
[1] => another some random text
)
[Key2] => Array
(
[0] => some radom text again
[1] => another some radom text again
)
)
不需要用正則表達式完全完成
使用preg_replace_callback來獲得whished結構的原始方法:
$pattern = '/^~ (\w+);\s*(.+?)\s*(?=\R~ \1;)/ms';
$res = array();
preg_replace_callback($pattern,
function ($m) use (&$res) { $res[$m[1]][] = $m[2]; },
$str);
print_r($res);
注意:我假設“隨機文本”可以是多行,如果不是這種情況,可以將模式更改為/^~ (\\w+);\\h*\\R?\\h*(\\N+?)\\h*(?=\\R~ \\1;)/m
\\R
是包含任何類型的換行符的原子組的快捷方式。
\\N
匹配除換行符以外的所有字符,無論采用哪種模式(是否使用單行)
您必須繼續嘗試preg_match_all
,因為preg_match_all
,這就是您所需要的工具。
原因是因為它執行全局搜索,而這恰恰是您這樣說時要表達的要求:
“但是似乎它只匹配第一次出現。”
這就是preg_match_all
目的。
無論如何,正則表達式的問題是反向引用\\1
。
當您捕獲text 1
,它會一直在尋找text 1
而不是您希望的text \\d
。
如果您可以提供更真實的數據樣本,則可以為其創建一個表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.