【问题标题】:Regex match for split拆分的正则表达式匹配
【发布时间】:2014-11-21 08:36:08
【问题描述】:
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);

【问题讨论】:

  • preg_spit("~[\s]=\"?[\s]\"?,~", $string);
  • 你不能用,分割,因为,在"foo, bar"

标签: php regex parsing split


【解决方案1】:

只需根据下面的正则表达式拆分您的输入字符串,

,\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

【讨论】:

    【解决方案2】:
    ,(?=(?:[^"]*"[^"]*")*[^"]*$)
    

    按此拆分。查看演示。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      相关资源
      最近更新 更多