我用这个preg_match来记录单词Telephone后面的信息:它只记录那一行的任何信息,我认为一旦它到达下一行的回车符,它就会停止记录。这很管用。
preg_match('/Telephone: (.*)/', $body, $Telephone);
现在我想用另一个关键词做一些类似的事情,但这可以跨越很多行,而不仅仅是一行,一旦信息结束,我需要下一行有另一个始终相同的关键词,它的地址。
下面是一个例子。
电话:090866544
地址:123 Hello Terrace
约翰斯敦
巴拉马古
西班牙
评论:
所以我希望它记录Address:和Comment:之间的所有内容,并且每个后面都有一个冒号。
这是我徒劳的尝试,但我发现很难把握预赛,所以我可能在做一些愚蠢的错误
preg_match('/Address: (.*?)Comment:/', $body, $address);
您可以使用s修饰符来允许点与换行符匹配,也可以使用这种模式:
$string =<<<LOD
Telephone: 090866544
Address: 123 Hello Terrace
Johnstown
Ballamagoo
Spain
Comment:
LOD;
$pattern = '~Address:s*+K(?>S++|s++(?!bComment:))+~';
if (preg_match($pattern, $string, $match))
$result = $match[0];
解释:
Address:s*+
K # reset all that have been matched before
(?> # open an atomic group
S++ # all that isn't a white character (space, tab, newline)
| # OR
s++(?!bComment:) # white characters not followed by "Comment:"
)+ # close the group and repeat one or more times