bor*_*ree 2 php regex parsing preg-match-all
我需要解析以下文本:
First: 1
Second: 2
Multiline: blablablabla
bla2bla2bla2
bla3b and key: value in the middle if strting
Fourth: value
Run Code Online (Sandbox Code Playgroud)
Value是一个字符串OR多行字符串,同时值可以包含"key:blablabla"substring.应该忽略这样的子字符串(不解析为单独的键值对).
请帮我使用正则表达式或其他算法.
理想的结果是:
$regex = "/SOME REGEX/";
$matches = [];
preg_match_all($regex, $html, $matches);
// $mathes has all key and value parsed pairs, including multilines values
Run Code Online (Sandbox Code Playgroud)
谢谢.
我尝试使用简单的正则表达式,但结果不正确,因为我不知道如何处理多行:
$regex = "/(.+?): (.+?)/";
$regex = "/(.+?):(.+?)\n/";
...
Run Code Online (Sandbox Code Playgroud)
您可以使用此模式执行此操作:
$pattern = '~(?<key>[^:\s]+): (?<value>(?>[^\n]*\R)*?[^\n]*)(?=\R\S+:|$)~';
preg_match_all($pattern, $txt, $matches, PREG_SET_ORDER);
print_r($matches);
Run Code Online (Sandbox Code Playgroud)