predisHow can I delete keys in Redis that match a specific pattern using PHP?
Using the scan
and del
commands, you can delete keys in Redis that match a specific pattern using PHP.
<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// Get keys matching pattern
$iterator = NULL;
$keys = $redis->scan($iterator, 'my-key-*');
// Delete keys
foreach ($keys as $key) {
$redis->del($key);
}
This code will search for all keys that begin with my-key-
and delete them.
Code explanation
$redis = new Redis();
- Instantiate a new Redis client$redis->connect('127.0.0.1', 6379);
- Connect to the Redis server$iterator = NULL;
- Set the iterator to NULL$keys = $redis->scan($iterator, 'my-key-*');
- Use thescan
command to get all keys that match the patternmy-key-*
foreach ($keys as $key) {
- Loop through all of the keys$redis->del($key);
- Use thedel
command to delete each key}
- End the loop
Helpful links
More of Predis
- How can I use the zscan command in PHP with Redis?
- How can I use PHP and Redis to retrieve a range of values from a sorted set?
- How do I use the hset array command in PHP with Redis?
- How can I use PHP and Redis to get multiple keys?
- How do I use the PHP Redis zrevrange command?
- How do I use the rpush command in PHP with Redis?
- How do I use yum to install php-redis?
- How can I use Predis with a cluster in PHP?
- How do I install PHP, Redis, and XAMPP?
- How do I install and configure a PHP Redis DLL on a Windows machine?
See more codes...