5.1 Assigning the Results of a Pattern Replacement


You want to assign a new variable to the result of a pattern replacement without modifying the old one.

Technique

PHP's functions are nondestructive, which means the new string is assigned to whatever variable you choose:

 <?php $str = "\t\tThis is not        a drill\n\n\n"; // compress multiple consecutive // whitespace characters into one $new_str = ereg_replace ("([\t\n ])+", "\1", $str); ?> 

Comments

The example is pretty trivial, but it points out a major problem that programmers encounter often. The regular expression functions in PHP do not actually affect the string on which they act, but rather return a new string based on the pattern and string that is given to them. Therefore, the following would be completely useless in a program:

 <?php ereg_replace ("([\t\n ])+", "\1", $str); ?> 

The string itself is never modified by ereg_replace() and the return value is not given to anything (it just wastes processor time).



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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