Home arrow PHP arrow Page 2 - Functions of Strings and Regular Expressions

Delimiting Special Regular Expression Characters - PHP

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).

  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



The functionpreg_quote()inserts a backslash delimiter before every character of special significance to regular expression syntax. These special characters include$^*( ) +={ } [ ] | \\ : < >. Its prototype follows:

string preg_quote(string str [, string delimiter])

The optional parameterdelimiter specifies what delimiter is used for the regular expression, causing it to also be escaped by a backslash. Consider an example:

$text = "Tickets for the bout are going for $500.";
echo preg_quote($text);

This returns the following:

Tickets for the bout are going for \$500\.

Replacing All Occurrences of a Pattern

Thepreg_replace()function operates identically toereg_replace(), except that it uses a Perl-based regular expression syntax, replacing all occurrences ofpatternwithreplacement, and returning the modified result. Its prototype follows:

mixed preg_replace(mixed pattern, mixed replacement, mixed str [, int limit])

The optional input parameterlimitspecifies how many matches should take place. Failing to setlimitor setting it to-1will result in the replacement of all occurrences. Consider an example:

$text = "This is a link to http://www.wjgilmore.com/.";
echo preg_replace("/http:\/\/(.*)\//",
"<a href="\${0}">\${0}</a>", $text);

This returns the following:

This is a link to
<a href="http://www.wjgilmore.com/">http:// www.wjgilmore.com/</a>.


Interestingly, thepatternandreplacementinput parameters can also be arrays. This function will cycle through each element of each array, making replacements as they are found. Consider this example, which could be marketed as a corporate report filter:

    $draft = "In 2007 the company faced plummeting revenues and scandal.";
    $keywords = array("/faced/", "/plummeting/", "/scandal/");
    $replacements = array("celebrated", "skyrocketing", "expansion");
    echo preg_replace($keywords, $replacements, $draft);

This returns the following:

In 2007 the company celebrated skyrocketing revenues and expansion.


Creating a Custom Replacement Function

In some situations you might wish to replace strings based on a somewhat more complex set of criteria beyond what is provided by PHP’s default capabilities. For instance, consider a situation where you want to scan some text for acronyms such as IRS and insert the complete name directly following the acronym. To do so, you need to create a custom function and then use the functionpreg_replace_callback()to temporarily tie it into the language. Its prototype follows:

mixed preg_replace_callback(mixed pattern, callback callback, mixed str
                            [, int limit])

Thepatternparameter determines what you’re looking for, while thestrparameter defines the string you’re searching. Thecallbackparameter defines the name of the function to be used for the replacement task. The optional parameterlimitspecifies how many matches should take place. Failing to setlimitor setting it to-1will result in the replacement of all occurrences. In the following example, a function namedacronym()is passed intopreg_replace_callback()and is used to insert the long form of various acronyms into the target string:


    // This function will add the acronym's long form
    // directly after any acronyms found in $matches
    function acronym($matches) {
$acronyms = array(
            'WWW' => 'World Wide Web',
            'IRS' => 'Internal Revenue Service',
            'PDF' => 'Portable Document Format');

        if (isset($acronyms[$matches[1]]))
            return $matches[1] . " (" . $acronyms[$matches[1]] . ")";
            return $matches[1];

    // The target text
    $text = "The <acronym>IRS</acronym>offers tax forms in
             <acronym>PDF</acronym>format on the <acronym>WWW</acronym>.";

    // Add the acronyms' long forms to the target text
    $newtext = preg_replace_callback("/<acronym>(.*)<\/acronym>/U", 'acronym',



This returns the following:

The IRS (Internal Revenue Service) offers tax forms
in PDF (Portable Document Format) on the WWW (World Wide Web).

Splitting a String into Various Elements Based on a Case-Insensitive Pattern

Thepreg_split()function operates exactly likesplit(), except thatpatterncan also be defined in terms of a regular expression. Its prototype follows:

array preg_split(string pattern, string string [, int limit [, int flags]])

If the optional input parameterlimitis specified, onlylimitnumber of substrings are returned. Consider an example:

    $delimitedText = "Jason+++Gilmore+++++++++++Columbus+++OH";
    $fields = preg_split("/\+{1,}/", $delimitedText);
    foreach($fields as $field) echo $field."<br />";

This returns the following:



Note  Later in this chapter, the section titled “Alternatives for Regular Expression Functions” offers several standard functions that can be used in lieu of regular expressions for certain tasks. In many cases, these alternative functions actually perform much faster than their regular expression counterparts.

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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- 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: