Prev | Current Page 309 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

Therefore this example will match strings such as sand and Sally
but not Melissa:
/sa\B/
The final example returns all instances of strings matching a dollar sign followed
by one or more digits:
/\$\d+\g
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(), and preg_split(). These functions are introduced in the
following sections.
Searching an Array
The preg_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
with p:
$foods = array("pasta", "steak", "fish", "potatoes");
$food = preg_grep("/^p/", $foods);
print_r($food);
?>
This returns the following:
CHAPTER 9 ?–  S TRINGS AND REGULAR EXPRESS IONS 243
Array ( [0] => pasta [3] => potatoes )
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 function array_values(),
introduced in Chapter 5.


Pages:
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321