PHP preg_grep Function: Usage, Parameters, Return Value, and Example
This article explains the PHP preg_grep() function, detailing its purpose, parameters, return value, and provides a complete code example that filters an array for floating‑point numbers using a regular expression in PHP scripts.
preg_grep() returns an array of elements from the input array that match the given regular‑expression pattern.
Parameters
pattern : The regex pattern to search for (string).
input : The input array.
flags : Optional flag; if set to PREG_GREP_INVERT, the function returns elements that do not match the pattern.
Return value : An array indexed by the original keys of the input array.
Example 1:
<?php
// Return all elements containing a floating‑point number
$array = array(1, 2, 3.4, 53, 7.9);
$fl_array = preg_grep("/^(
\d+)?\.\d+$/", $array);
print_r($fl_array);
?>Output:
Array
(
[2] => 3.4
[4] => 7.9
)Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
