Home > Article > Backend Development > Can PHP regularity match arrays?
php regular expression can match arrays. In PHP, you can use the preg_grep() function to match elements in an array using regular expressions; this function can search for each element in the array and return an array composed of all elements that match the regular expression. The syntax "preg_grep (regular expression, array, $flags)"; the parameter "$flags" is optional. When the value is set to "PREG_GREP_INVERT", an array consisting of elements in the array that do not match the regular expression will be returned.
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php regular expression can match arrays.
In PHP, when it comes to regular matching, we think of strings. In fact, in addition to matching strings, regular expressions can also be used to match arrays.
In PHP, you can use the preg_grep() function to match elements in an array using regular expressions.
preg_grep() function can search all elements in an array and return an array composed of all elements that match the regular expression. The syntax format of this function is as follows:
preg_grep($pattern, $input [, $flags = 0 ])
The parameter description is as follows:
perg_grep() function will traverse each element in the $input array, match the element with the pattern $pattern, and then return the elements that match successfully or fail to match.
Example 1: Return the specified matching element in the array
<?php header('content-type:text/html;charset=utf-8'); $array = array(1, 2, 3.4, 53, 7.9); echo "原数组:"; var_dump($array); // 返回所有包含浮点数的元素 $fl_array = preg_grep("/^(\d+)?\.\d+$/", $array); echo "返回所有包含浮点数的元素:"; var_dump($fl_array); ?>
Example 2:
<?php header('content-type:text/html;charset=utf-8'); $test_arr = array( 'PHP中文网', 'http://www.php.cn/', 'php教程', 'abcdefg' ); $preg = '/^[a-z]/'; $preg_arr_1 = preg_grep($preg, $test_arr); $preg_arr_2 = preg_grep($preg, $test_arr, PREG_GREP_INVERT); echo '<pre class="brush:php;toolbar:false">'; var_dump($preg_arr_1); var_dump($preg_arr_2); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Can PHP regularity match arrays?. For more information, please follow other related articles on the PHP Chinese website!