doulouxun6756 2013-07-26 16:09
浏览 43
已采纳

php regex:使用引号进行匹配,但不捕获它们

I'm unsure if I should be using preg_match, preg_match_all, or preg_split with delim capture. I'm also unsure of the correct regex.

Given the following:

$string = " ok 'that\\'s cool' \"yeah that's \\\"cool\\\"\"";

I want to get an array with the following elems:

[0] = "ok"
[1] = "that\'s"
[2] = "yeah that's \"cool\""
  • 写回答

3条回答 默认 最新

  • dongzhen4180 2013-07-26 16:14
    关注

    You can not do this with a regular expression because you're trying to parse a non-context-free grammar. Write a parser.

    Outline:

    • read character by character, if you see a \ remember it.
    • if you see a " or ' check if the previous character was \. You now have your delimiting condition.
    • record all the tokens in this manner

    Your desired result set seems to trim spaces, you also lost a couple of the \s, perhaps this is a mistake but it can be important.

    I would expect:

    [0] = " ok " // <-- spaces here
    [1] = "that\\'s cool"
    [2] = " \"yeah that's \\\"cool\\\"\"" // leading space here, and \" remains
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b