猿问

我有 preg_match_all 函数的问题

我不知道如何从此代码中获取全行内容。



$str = '


#chapter 1: title 1


content chapter 1 line 1

content chapter 1 line 2

content chapter 1 line 3

content chapter 1 line 4


#chapter 2: title 2


content 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+)。


我怎样才能获得全行内容?!非常感谢。


慕标琳琳
浏览 122回答 1
1回答

慕哥9229398

目前您只匹配一行。您可以使用重复模式来匹配所有不以 #chapter 开头的行,使用负前瞻:#Chapter\h+\d+:\h+title\h+\d+\K(?:\R(?!#chapter).*)*解释#Chapter&nbsp;字面匹配\h+\d+:&nbsp;匹配 1+ 个水平空白字符、1+ 个数字和&nbsp;:\h+title\h+\d+匹配 匹配 1+ 个水平空白字符,title匹配 1+ 个水平空白字符和 1+ 个数字\K&nbsp;忘记匹配的内容(?:&nbsp;非捕获组\R(?!#chapter).*&nbsp;匹配unicode换行序列并断言直接在右边的不是#chapter)*&nbsp;关闭捕获组并重复 0+ 次例如:preg_match_all('/#Chapter\h+\d+:\h+title\h+\d+\K(?:\R(?!#chapter).*)*/i',$str, $match);print_r($match[0]);结果Array(&nbsp; &nbsp; [0] =>&nbsp;content chapter 1 line 1content chapter 1 line 2content chapter 1 line 3content chapter 1 line 4&nbsp; &nbsp; [1] =>&nbsp;content chapter 2 line 1)
随时随地看视频慕课网APP
我要回答