YouTip LogoYouTip

Php Preg_Grep

## PHP preg_grep() Function The `preg_grep()` function in PHP is a powerful built-in tool used to search an array for elements that match a specific regular expression pattern. It filters the input array and returns a new array containing only the matching elements (or non-matching elements, depending on the flags used). --- ### Syntax ```php array preg_grep ( string $pattern , array $input [, int $flags = 0 ] ) ``` ### Parameters * **`$pattern`**: The regular expression pattern to search for, represented as a string. * **`$input`**: The input array containing strings or numbers to be evaluated. * **`$flags`**: Optional. If set to `PREG_GREP_INVERT`, this function returns an array containing elements from the input array that **do not** match the given pattern. ### Return Value Returns an array indexed using the keys from the `$input` array. The returned array preserves the original keys of the matched elements. --- ### Code Examples #### Example 1: Filtering Floating-Point Numbers In this example, we use `preg_grep()` to extract only the floating-point numbers from an array containing integers and floats. ```php ``` **Output:** ```text Array ( => 3.4 => 7.9 ) ``` *Note: As shown in the output, the original array keys (`2` and `4`) are preserved in the filtered result.* --- #### Example 2: Inverting the Search with `PREG_GREP_INVERT` By using the `PREG_GREP_INVERT` flag, you can retrieve all elements that **do not** match the regular expression. ```php ``` **Output:** ```text Array ( => PHP => JavaScript => Python => Ruby ) ``` --- ### Key Considerations 1. **Key Preservation**: `preg_grep()` preserves the original keys of the input array. If you need to reset the array keys to sequential integers (0, 1, 2...), wrap the result in `array_values()`: ```php $reindexed_array = array_values(preg_grep($pattern, $input)); ``` 2. **Type Coercion**: Elements in the input array are temporarily cast to strings during the matching process. 3. **Memory Efficiency**: Since `preg_grep()` processes the entire array at once, it is highly efficient for filtering large datasets compared to manual `foreach` loops combined with `preg_match()`.
← Php Preg_QuoteSvn Branch β†’