如何使用 php 删除指定字符串单词



如何删除字符串.我想找到 2018 年的字符串,然后我想删除字符串,直到 ,

{"2018-1-8":0,"2018-1-9":0,"2018-1-10":0,"2019-1-1":0,"2019-1-15":0}

我怎么能这样显示

{"2019-1-1":0,"2019-1-15":0}

注意:我想删除"2018-1-8":0,"2018-1-9":0,"2018-1-10":0,

此字符串是有效的JSON,您可以使用json_decode()进行解析。然后,您可以根据需要修改数据:

// Your string
$json = '{"2018-1-8":0,"2018-1-9":0,"2018-1-10":0,"2019-1-1":0,"2019-1-15":0}';
// Get it as an array
$data = json_decode($json, true);
// Pass by reference
foreach ($data as $key => &$value) {
// Remove if key contains '2018'
if (strpos($key, '2018') !== false) {
unset($data[$key]);
}
}
// Return the updated JSON
echo json_encode($data);
// Output: {"2019-1-1":0,"2019-1-15":0}

使用array_walk()的另一种解决方案:

$data = json_decode($json, true);
array_walk($data, function ($v, $k) use (&$data) {
if (strpos($k, '2018') !== false) { unset($data[$k]); }
});
echo json_encode($data);
// Output: {"2019-1-1":0,"2019-1-15":0}

另请参阅:

  • 通过引用传递
  • strpos()
  • unset()
  • json_encode()

试试这个也许:

// Your string
$string = "{"2018-1-8":0,"2018-1-9":0,"2018-1-10":0,"2019-1-1":0,"2019-1-15":0}";
// Transform it as array
$array = json_decode($string);
// Create a new array
$new_array = array();
// Now loop through your array
foreach ($array as $date => $value) {
// If the first 4 char of your $date is not 2018, then add it in new array
if (substr($date, 0, 4) !== "2018")
$new_array[$date] = $value;
}
// Now transform your new array in your desired output
$new_string = json_encode($new_array);

var_dump($new_string);的输出{"2019-1-1":0,"2019-1-15":0}

相关内容

  • 没有找到相关文章

最新更新