PHP Regex 查找并替换所有以特定字符开头和结尾的字符串

说到正则表达式,我是个新手。我有一个包含时间戳的 json 字符串,我想删除date字符串中所有出现的字段。


美化后的 json 字符串如下所示:


{

  "abc": 157,

  "efg": 1,

  "hij": "1",

  "klm": "0.00",

  "created_at": {

    "date": "2020-04-08 12:53:34.682759",

    "timezone_type": 3,

    "timezone": "UTC"

  },

  "updated_at": {

    "date": "2020-04-08 12:53:34.682759",

    "timezone_type": 3,

    "timezone": "UTC"

  }

}

"date": "我想删除所有以开头和结尾的字符串",


所以输出看起来像下面这样:


{

  "abc": 157,

  "efg": 1,

  "hij": "1",

  "klm": "0.00",

  "created_at": {

    "timezone_type": 3,

    "timezone": "UTC"

  },

  "updated_at": {

    "timezone_type": 3,

    "timezone": "UTC"

  }

}

我知道preg_match_all实际上可以帮助找到所有匹配项,但是,我发现在构建模式时遇到困难,尤其是我的模式包含逗号和双引号。


料青山看我应如是
浏览 119回答 1
1回答

交互式爱情

正则表达式(或任何其他字符串函数)不是编辑 JSON 字符串的方式!您必须将其解码为数组,然后对其进行编辑,最后将其重新编码为 JSON。$json = <<<'JSON'{&nbsp; "abc": 157,&nbsp; "efg": 1,&nbsp; "hij": "1",&nbsp; "klm": "0.00",&nbsp; "created_at": {&nbsp; &nbsp; "date": "2020-04-08 12:53:34.682759",&nbsp; &nbsp; "timezone_type": 3,&nbsp; &nbsp; "timezone": "UTC"&nbsp; },&nbsp; "updated_at": {&nbsp; &nbsp; "date": "2020-04-08 12:53:34.682759",&nbsp; &nbsp; "timezone_type": 3,&nbsp; &nbsp; "timezone": "UTC"&nbsp; }}JSON;$arr = json_decode($json, true);function delete_key(&$arr, $key) {&nbsp; &nbsp; foreach($arr as $k => &$v) {&nbsp; &nbsp; &nbsp; &nbsp; if ( $k === $key ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; unset($arr[$k]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if ( is_array($v) ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; delete_key($v, $key);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}delete_key($arr, 'date');print_r(json_encode($arr, JSON_PRETTY_PRINT));演示
打开App,查看更多内容
随时随地看视频慕课网APP