dongsuoxi1790 2014-05-08 18:06
浏览 43
已采纳

字符串之间的Preg_Replace字符

Im trying to write the most efficient way to escape double quote marks (") from a a json feed that contains quote marks in incorrect places.

ie

{ "count": "1", "query": "www.mydomain.com/watchlive/type/livedvr/event/69167/"%20%20sTyLe=X:eX/**/pReSsIoN(window.location=56237)%20"", "error": "500"}

there are three keys above - count, query and error. The value in "query" is invalid as the extra double quotes are rendering a invalid json.

If I escape it using \" then the json is valid and can be parsed by the PHP engine, but since the json can have over 5000 sets of data, I cant just manually go and change the offending line(s).

I know that using a combination of preg_match and str_replace will work, but its very messy and not maintainable code. I need the reg_ex to use in something like this

$buffer = '{ "count": "1", "query": "www.mydomain.com/watchlive/type/livedvr/event/69167/"%20%20sTyLe=X:eX/**/pReSsIoN(window.location=56237)%20"", "error": "500"}'

preg_match('/(query": ")(.*)(", "error)/', $buffer , $match);

Thanks in advance

  • 写回答

1条回答 默认 最新

  • dpoh61610 2014-05-08 18:23
    关注

    Match and replace using this expression:

    (?:"query"\s*:\s*"|(?<!\A)\G)[^"]*\K"(?=.*?",)
    \"
    

    In PHP, this would use preg_replace():

    $buffer = preg_replace('/(?:"query"\s*:\s*"|(?<!\A)\G)[^"]*\K"(?=.*?",)/', '\"', $buffer);
    var_dump($buffer);
    

    Explanation:

    (?:                # Start non-capturing group
      "query"\s*:\s*"  # Match "query":" literally, with optional whitespace  
     |                 # OR
      (?<!\A)          # Make sure we are not at the beginning of the string
      \G               # Start at the end of last match
    )                  # End non-capturing
    [^"]*              # Go through non-" characters
    \K                 # Remove everything to the left from the match
    "                  # Match " (this will be the only thing matched and replaced)
    (?=                # Start lookahead group
      .*?",            # Lazily match up until the ", (this is the end of the JSON value)
    )                  # End lookahead group
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!