Search and Replace


 POSIX:   egreg-replace () PCRE:   preg-replace() 


Searching within strings is one thing; replacing all occurrences with something else is completely different. Using regular expressions, this is relatively easy; you just have to know the respective function names:

  • For POSIX, use ereg_replace() and eregi_replace()

  • For PCRE, use preg_replace()

Replacing Matches Using POSIX (ereg_replace.php) and PCRE (preg_replace.php)

POSIX:

 <?php   $string = '02/01/06';   echo ereg_replace(     '([0-9][0-9]?)/([0-9][0-9]?)/([0-9][0-9]?)',     '\\2/\\1/\\3',     $string   ); ?> 

PCRE:

 <?php   $string = '02/01/06';   echo preg_replace(     '#(\d{1,2})/(\d{1,2})/(\d{1,2})#',     '$2/$1/$3',     $string   ); ?> 

Within the regular expression for the replace term, you can use references to subpatterns. The complete match is referred to by \0 in POSIX and $0 in PCRE. Then count parentheses from inside to outside, from left to right: The contents of the first parentheses are referenced by \1 or $1, the second parentheses are accessed using \2 or $2, and so on.

With this in mind, the replacement can be done. In the example, a U.S. date (month/day/year) is converted to a U.K. date (day/month/year).

TIP

The regular expression in the preceding code does not use the / delimiter for the regular expression because the regular expression itself contains slashes that would then need escaping. However, by choosing another delimiter (for example: #), the escaping of slashes can be avoided.


If you have a static pattern, without any quantifiers or special characters, using str_replace() is almost always faster. The parameter order for this is: first the string(s) to search for; then the replacement(s); and, finally, the string where the search and replace shall take place. You can provide strings or arrays of strings in the first two parameters. The following code removes all punctuation from the text.

Replacing Without Regular Expressions (str_replace.php)
 <?php   $string = 'To be, or not to be; that\'s the question?!';   echo str_replace(     array('.', ',', ':', ';', '!', '?'),     '',      $string   ); ?> 




PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net