PHP Predis:如何获取/删除包含特殊字符的键?

时间:2014-08-27 16:59:05

标签: php predis

我需要删除一个包含一些特殊键的键(在我的方括号中):

我执行以下操作,但它不起作用:

$this->redis;    
$keys = $this->redis->keys("*");
foreach ($keys as $key) {

    // keys are in the following format:   
    //    vir3_data_cache[zones_cdc_shifting_series_2013_5][1]

    $this->redis->del($key);
    // no key was deleted
}

我也尝试引用密钥,但没有成功:

$this->redis;    
$keys = $this->redis->keys("*");
foreach ($keys as $key) {

    // keys are in the following format:   
    //    vir3_data_cache[zones_cdc_shifting_series_2013_5][1]

    $quotedKey = addslashes(addslashes($key));
    $this->redis->del($quotedKey);
    // no key was deleted
}

2 个答案:

答案 0 :(得分:2)

<强>解决即可。问题与这样一个事实有关:在执行任何操作之前,predis会在每个键的开头自动插入一个配置的前缀(在我的情况下&#39; vir3_data_cache&#39;)。但keys("*")命令不会从密钥中删除前缀。

所以我需要执行以下操作才能使代码正常工作:

$prefix = $this->redis->getOptions()->__get('prefix')->getPrefix();

$keys = $this->redis->keys("*");
$removed = 0;
foreach ($keys as $key) {
    if (substr($key, 0, strlen($prefix)) == $prefix) {
        $key = substr($key, strlen($prefix));
    }              
}

答案 1 :(得分:0)

使用phpredis时,您可以获取前缀并删除键的模式:

<?php
...

$prefix = $redisClient->getOption(Redis::OPT_PREFIX);
$redisClient->delete(array_map(
    function ($key) use ($prefix) {
        return str_replace($prefix, '', $key);
    }, $redisClient->keys('*'))
);