来自Array with Multine的PHP正则表达式preg_match与所有块都不匹配

想知道是否有人可以帮助我使用以下正则表达式,我无法匹配块多线CF. {Coordonnees Abonne}:在PHP的preg_match函数中使用时.

奇怪的是,当我在线进行正则表达式时,尽管该块在另一组regex101 example中,它似乎仍然有效

这是代码source code

<?PHP
$response = array(
      1  => 'CF.{Temps}: 1',
      2  => 'CF.{Etat}: return',
      3  => 'CF.{Code}: 2',
      4  => 'CF.{Values}: plaque',
      5  => '',
      6  => 'CF.{Coordonnees}: LA PERSONNE',
      7  => '    ',
      8  => '    10000  LA VILLE',
      9  => '    ',
      10 => '    0500235689',
      11 => '    0645788923',
      12 => '    Login : test@mail.com',
      13 => '    Password : PassWord!',
      14 => '',
      15 => 'CF.{Groupe}: 3',
      16 => 'CF.{Date}: 4',
);

print_r(parseResponseBody($response));

function parseResponseBody(array $response, $delimiter = ':')
{
    $responseArray = array();
    $lastkey = null;

    foreach ($response as $line) {
        if(preg_match('/^([a-zA-Z0-9]+|CF\.{[^}]+})' . $delimiter . '\s(.*)|([a-zA-Z0-9].*)$/', $line, $matches)) {
                $lastkey = $matches[1];
                $responseArray[$lastkey] = $matches[2];
        }
    }

    return $responseArray;
}
?>

输出

Array
(
    [CF.{Temps}] => 1
    [CF.{Etat}] => return
    [CF.{Code}] => 2
    [CF.{Values}] => plaque
    [CF.{Coordonnees}] => LA PERSONNE
    [] => 
    [CF.{Groupe}] => 3
    [CF.{Date}] => 4
)

并且我需要提取想要的最终结果:

Array
(
    [CF.{Temps}] => 1
    [CF.{Etat}] => return
    [CF.{Code}] => 2
    [CF.{Values}] => plaque
    [CF.{Coordonnees}] => LA PERSONNE

        10000  LA VILLE

        0500235689
        0645788923
        Login : test@mail.com
        Password : PassWord!
    [CF.{Groupe}] => 3
    [CF.{Date}] => 4
)

解决方法:

您必须检查迭代中的当前值是否以块开始.但不是两个在同一时间:

function parseResponseBody(array $response, $delimiter = ':') {
    $array = [];
    $lastIndex = null;
    foreach ($response as $line) {
        if (preg_match('~^\s*(CF\.{[^}]*})' . $delimiter . '\s+(.*)~', $line, $matches))
            $array[$lastIndex = $matches[1]] = $matches[2];
        elseif ((bool) $line)
            $array[$lastIndex] .= PHP_EOL . $line;
    }
    return $array;
}

Live demo

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...