Home arrow PHP arrow Functions of Strings and Regular Expressions

Functions of Strings and Regular Expressions

In this second part of a five-part series on strings and regular expressions in PHP, you'll learn about regular expression functions and a variety of string-specific functions. This article is excerpted from chapter nine of the book Beginning PHP and Oracle: From Novice to Professional, written by W. Jason Gilmore and Bob Bryla (Apress; ISBN: 1590597702).

TABLE OF CONTENTS:
  1. Functions of Strings and Regular Expressions
  2. Delimiting Special Regular Expression Characters
  3. Other String-Specific Functions
  4. Calculating the Similarity Between Two Strings
By: Apress Publishing
Rating: starstarstarstarstar / 2
June 24, 2010

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
   
$foods = array("pasta", "steak", "fish", "potatoes");
   
$food = preg_grep("/^p/", $foods);
   
print_r($food);
?>

This returns the following:

--------------------------------------------
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 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]
               [, int flags [, int offset]]])

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
   
$line = "vim is the greatest word processor ever created!";
   
if (preg_match("/\bVim\b/i", $line, $match)) print "Match found!";
?>

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
                  
[, int order])

Theorder parameter accepts two values:

  1. PREG_PATTERN_ORDERis the default if the optionalorder parameter is not included.PREG_PATTERN_ORDERspecifies the order in the way that you might think most logical:$pattern_array[0]is an array of all complete pattern matches,$pattern_array[1]is an array of all strings matching the first parenthesized regular expression, and so on.
  2. PREG_SET_ORDERorders the array a bit differently than the default setting.$pattern_array[0]contains elements matched by the first parenthesized regular expression,$pattern_array[1]contains elements matched by the second parenthesized regular expression, and so on.

Here’s how you would usepreg_match_all()to find all strings enclosed in bold HTML tags:

<?php
    $userinfo = "Name: <b>Zeev Suraski</b> <br> Title: <b>PHP Guru</b>";
    preg_match_all("/<b>(.*)<\/b>/U", $userinfo, $pat_array);
    printf("%s <br /> %s", $pat_array[0][0], $pat_array[0][1]);
?>

This returns the following:

--------------------------------------------
Zeev Suraski
PHP Guru

--------------------------------------------



 
 
>>> More PHP Articles          >>> More By Apress Publishing
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: