我不知道如何從此代碼中獲取全行內容。$str = '#chapter 1: title 1content chapter 1 line 1content chapter 1 line 2content chapter 1 line 3content chapter 1 line 4#chapter 2: title 2content chapter 2 line 1';preg_match_all('/#Chapter ([0-9]+.?[0-9]?)\s?(<([0-9]+)>)?:(.*)(\s+.+\s+)/i',$str, $match);我試過這段代碼,這得到了這樣的內容:$match[5][0]: 內容章節 1 第 1 行$match[5][1]:內容第二章第二行問題在: (\s+.+\s+)。我怎樣才能獲得全行內容?!非常感謝。
1 回答

慕哥9229398
TA貢獻1877條經驗 獲得超6個贊
目前您只匹配一行。
您可以使用重復模式來匹配所有不以 #chapter 開頭的行,使用負前瞻:
#Chapter\h+\d+:\h+title\h+\d+\K(?:\R(?!#chapter).*)*
解釋
#Chapter
字面匹配\h+\d+:
匹配 1+ 個水平空白字符、1+ 個數字和:
\h+title\h+\d+
匹配 匹配 1+ 個水平空白字符,title
匹配 1+ 個水平空白字符和 1+ 個數字\K
忘記匹配的內容(?:
非捕獲組\R(?!#chapter).*
匹配unicode換行序列并斷言直接在右邊的不是#chapter)*
關閉捕獲組并重復 0+ 次
例如:
preg_match_all('/#Chapter\h+\d+:\h+title\h+\d+\K(?:\R(?!#chapter).*)*/i',$str, $match);
print_r($match[0]);
結果
Array
(
[0] =>
content chapter 1 line 1
content chapter 1 line 2
content chapter 1 line 3
content chapter 1 line 4
[1] =>
content chapter 2 line 1
)
- 1 回答
- 0 關注
- 141 瀏覽
添加回答
舉報
0/150
提交
取消