Page 596 - Beginning PHP 5.3
P. 596

Part III: Using PHP in Practice
                   You can also pass an array of target strings for  preg_replace()  to work on, much like using
                 preg_grep() . If you do this,  preg_replace()  returns the array of strings with any matched text
                 replaced by the replacement text:

                    $text = array(
                     “Mouse mat: $3.99”,
                     “Keyboard cover: $4.99”,
                     “Screen protector: $5.99”
                    );

                    $newText = preg_replace( “/\\$\d+\.\d{2}/”, “Only $0”, $text );
                    echo “ < pre > ”;
                    print_r( $newText );

                    echo “ < /pre > ”;
                   This code displays:
                    Array
                    (
                        [0] = >  Mouse mat: Only $3.99
                        [1] = >  Keyboard cover: Only $4.99
                        [2] = >  Screen protector: Only $5.99
                    )

                    preg_replace()  has a couple more tricks up its sleeve. You can pass an array of regular expression
                 strings to the function, and it will match and replace each expression in turn with the replacement string:
                    $text = “The wholesale price is $89.50. “ .
                     “The product will be released on Jan 16, 2010.”;

                    $patterns = array(
                     “/\\$\d+\.\d{2}/”,
                     “/\w{3} \d{1,2}, \d{4}/”
                    );

                    echo preg_replace( $patterns, “[CENSORED]”, $text );

                   This script outputs the following:

                    The wholesale price is [CENSORED]. The product will be released on

                    [CENSORED].
                   If you also pass an array of replacement strings, the matched text from each expression in the
                 expressions array is replaced by the corresponding string in the replacements array:

                     $text = “The wholesale price is $89.50. “ .
                     “The product will be released on Jan 16, 2010.”;

                    $patterns = array(
                     “/\\$\d+\.\d{2}/”,
                     “/\w{3} \d{1,2}, \d{4}/”
                    );



              558





                                                                                                      9/21/09   6:17:59 PM
          c18.indd   558
          c18.indd   558                                                                              9/21/09   6:17:59 PM
   591   592   593   594   595   596   597   598   599   600   601