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 thescancommand to get all keys that match the patternmy-key-*foreach ($keys as $key) {- Loop through all of the keys$redis->del($key);- Use thedelcommand 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 troubleshoot a "PHP Redis went away" error?
- How can I use PHP and Redis to retrieve data from a sorted set using ZRANGEBYSCORE?
- How do I install and configure a PHP Redis DLL on a Windows machine?
- How can I use PHP to increment values in Redis using ZINCRBY?
- How do I install PHP Redis on Ubuntu 20.04?
- How do I use the PHP Redis zrevrange command?
- How can I use Predis with a cluster in PHP?
- How can I configure TLS encryption for a connection between PHP and Redis?
- How do I check the version of PHP Redis?
See more codes...