正则表达式匹配拆分

时间:2014-11-21 08:36:09

标签: php regex parsing split

fontSize=16.0, fontFamily=sans, align=0, color=FF0000, text="foo, bar"

我需要匹配吐。输出将是

array(
  'fontSize'=>'16.0',
  'fontFamily'=>'sans',
  'align'=>'0',
  'color'=>'FF0000',
  'text'=>'foo, bar'
);

接下来我试过了,但这很糟糕:

preg_spit("~[\s]="?[\s]"?,~", $string);

2 个答案:

答案 0 :(得分:0)

根据以下正则表达式分割您的输入字符串,

,\s(?![^=]*")

DEMO

<?php
$str = 'fontSize=16.0, fontFamily=sans, align=0, color=FF0000, text="foo, bar"';
$regex = '~,\s(?![^=]*")~';
$splits = preg_split($regex, $str);
print_r($splits);
?>

<强>输出:

Array
(
    [0] => fontSize=16.0
    [1] => fontFamily=sans
    [2] => align=0
    [3] => color=FF0000
    [4] => text="foo, bar"
)

正则表达式:

,                        ','
\s                       whitespace (\n, \r, \t, \f, and " ")
(?!                      look ahead to see if there is not:
  [^=]*                    any character except: '=' (0 or more
                           times)
  "                        '"'
)                        end of look-ahead

答案 1 :(得分:0)

,(?=(?:[^"]*"[^"]*")*[^"]*$)

由此分开。参见演示。

http://regex101.com/r/xN4qL9/1