PHP’s Regular Expression Functions (Perl Compatible) PHP offers seven functions for searching strings using Perl-compatible regular expressions:preg_grep(),preg_match(),preg_match_all(),preg_quote(),preg_replace(),preg_replace_callback(), andpreg_split(). These functions are introduced in the following sections. Searching an Array Thepreg_grep()function searches all elements of an array, returning an array consisting of all elements matching a certain pattern. Its prototype follows: array preg_grep(string pattern, array input [, flags]) Consider an example that uses this function to search an array for foods beginning withp: <?php This returns the following: -------------------------------------------- Note that the array corresponds to the indexed order of the input array. If the value at that index position matches, it’s included in the corresponding position of the output array. Otherwise, that position is empty. If you want to remove those instances of the array that are blank, filter the output array through the functionarray_values(), introduced in Chapter 5. The optional input parameterflagswas added in PHP version 4.3. It accepts one value,PREG_GREP_INVERT. Passing this flag will result in retrieval of those array elements that do not match the pattern. Searching for a Pattern Thepreg_match()function searches a string for a specific pattern, returningTRUEif it exists, andFALSEotherwise. Its prototype follows: int preg_match(string pattern, string string [, array matches] The optional input parameterpattern_arraycan contain various sections of the subpatterns contained in the search pattern, if applicable. Here’s an example that usespreg_match()to perform a case-insensitive search: <?php For instance, this script will confirm a match if the wordVimorvim is located, but notsimplevim,vims, orevim. Matching All Occurrences of a Pattern Thepreg_match_all()function matches all occurrences of a pattern in a string, assigning each occurrence to an array in the order you specify via an optional input parameter. Its prototype follows: int preg_match_all(string pattern, string string, array pattern_array Theorder parameter accepts two values:
Here’s how you would usepreg_match_all()to find all strings enclosed in bold HTML tags: <?php This returns the following: --------------------------------------------
blog comments powered by Disqus |
|
|
|
|
|
|
|