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条)

报告相同问题?