我不知道如何从此代码中获取全行内容。$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 关注
- 121 浏览
添加回答
举报
0/150
提交
取消