What are some potential pitfalls when using regex to filter array keys in PHP?

One potential pitfall when using regex to filter array keys in PHP is that the regex pattern may not match the keys as expected, leading to unintended results. To solve this, it is important to carefully test the regex pattern against the array keys to ensure it accurately filters the desired keys. Additionally, using the preg_grep function can simplify the process of filtering array keys with regex patterns.

// Sample array
$array = ['key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'];

// Regex pattern to filter keys starting with 'key'
$pattern = '/^key/';

// Filter array keys using preg_grep
$filteredKeys = preg_grep($pattern, array_keys($array));

// Output filtered keys
print_r($filteredKeys);