dtsnx44260 2014-07-03 16:07
浏览 50
已采纳

preg_split一个字符串,不是单引号之间的空格

I am trying to pref_split a string by spaces not between single quotes.

This is the string I am working with:

'physical memory %'=92%;99;100 'physical memory'=29.69GB;31.68;32;0;32

The following regex pattern successfully matches the space that I want to split by:

/\x20(?=[^']*('[^']*'[^']*)*$)\g

The problem I am having is that I wrote this string using http://www.regexr.com/ which is specific to JavaScript regex and I need this to work in PHP.

This is the PHP code I have so far but it is throwing an error:

preg_split("/\x20(?=[^']*('[^']*'[^']*)*$)/g", "'physical memory %'=92%;99;100 'physical memory'=29.69GB;31.68;32;0;32");

Error:

preg_split(): Unknown modifier 'g'

If I remove the / and /g I get the following error:

preg_match_all(): Compilation failed: nothing to repeat at offset 0

My guess is that for some reason the regex in PHP isn't matching any values so it is unable to split the string. Can someone help with how to properly do this?

Thank you.

  • 写回答

2条回答 默认 最新

  • dongtuo8170 2014-07-03 16:20
    关注

    Remove the g (global) modifier from your regular expression.

    preg_split("/\x20(?=[^']*('[^']*'[^']*)*$)/", "'physical memory %'=92%;99;100 'physical memory'=29.69GB;31.68;32;0;32");
    

    Working Demo

    Although your regular expression will work, you could use the following which makes this a lot easier to ignore the space characters in quotations.

    $results = preg_split("/'[^']*'(*SKIP)(*F)|\x20/", $str);
    print_r($results);
    

    Explanation:

    The idea is to skip content in single quotations. I first match the quotation followed by any character except ', followed by a single quotation, and then make the subpattern fail and force the regular expression engine to not retry the substring with another alternative with (*SKIP) and (*F) backtracking control verbs.

    Output

    Array
    (
        [0] => 'physical memory %'=92%;99;100
        [1] => 'physical memory'=29.69GB;31.68;32;0;32
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真