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

时间:2018-08-28 08:28:18

标签: php

如何删除string。我想找到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,

2 个答案:

答案 0 :(得分:1)

也许尝试:

// 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}

答案 1 :(得分:1)

此字符串是有效的 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}

另请参阅: