PHP preg_replace() Function

Description

preg_replace - Perform a regular expression search and replace.

Syntax

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )

Parameter

  • pattern - The pattern to search for. It can be either a string or an array with strings.
  • replacement - The string or an array with strings to replace. If this parameter is a string and the pattern parameter is an array, all patterns will be replaced by that string. If both pattern and replacement parameters are arrays, each pattern will be replaced by the replacement counterpart. If there are fewer elements in the replacement array than in the pattern array, any extra patterns will be replaced by an empty string.
  • subject - The string or an array with strings to search and replace.
  • limit - The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).
  • count - If specified, this variable will be filled with the number of replacements done.

Return Values

preg_replace() returns an array if the subject parameter is an array, or a string otherwise.

If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.

Example 1

The second parameter is plain text, but can contain $n to insert the text matched by subpattern n of your regexp rule. If you have no subpatterns, you should use $0 to use the matched text, like this:


<?PHP// w  w  w . ja v a  2s . co m
     $a = "PHP php";
     $b = preg_replace("/php/i", "Got word: $0\n", $a);
     print $b;
?>

The code above generates the following result.

Example 2

If you are using subpatterns, $0 is set to the whole match, then $1, $2, and so on are set to the individual matches for each subpattern.


<?PHP/*  w  ww  . j av  a  2 s  .  c o  m*/
     $match = "/(java|php) vs (book|demo)/";
     $input = "java php vs book demo";
     print preg_replace($match, "Matched $0, $1, and $2\n", $input);

     $a = "Foo moo boo tool foo";
     $b = preg_replace("/[A-Za-z]oo\b/e", 'strtoupper("$0")', $a);
     print $b;
?>

The code above generates the following result.

Example 3

We can pass a fourth parameter to preg_replace() to specify the maximum number of replacements you want to make. For example:


<?PHP// ww w .j av  a 2s  . c  o  m
     $a = "PHP php PhP";
     $b = preg_replace("/php/i", 'strtoupper("$0")', $a, 2);
     print $b;
?>

Only the first two matches have been replaced, thanks to the fourth parameter being set to 2.

The code above generates the following result.

Example 4

Using backreferences followed by numeric literals


<?php//  w  ww  .  j  a  va2s  . co m
    $string = 'April 15, 2013';
    $pattern = '/(\w+) (\d+), (\d+)/i';
    $replacement = '${1}1,$3';
    echo preg_replace($pattern, $replacement, $string);
?>

The code above generates the following result.

Example 5

Using indexed arrays with preg_replace()

<?php//from  w  ww.  ja va  2s. c  o m
    $string = 'The quick brown fox jumped over the lazy dog.';
    $patterns = array();
    $patterns[0] = '/quick/';
    $patterns[1] = '/brown/';
    $patterns[2] = '/fox/';
    $replacements = array();
    $replacements[2] = 'bear';
    $replacements[1] = 'black';
    $replacements[0] = 'slow';
    echo preg_replace($patterns, $replacements, $string);
?>

By ksorting patterns and replacements.


<?php//from w  ww . java  2  s .  co m
    $string = 'The quick brown fox jumped over the lazy dog.';
    $patterns = array();
    $patterns[0] = '/quick/';
    $patterns[1] = '/brown/';
    $patterns[2] = '/fox/';
    $replacements = array();
    $replacements[2] = 'bear';
    $replacements[1] = 'black';
    $replacements[0] = 'slow';
    echo preg_replace($patterns, $replacements, $string);

    ksort($patterns);
    ksort($replacements);
    echo preg_replace($patterns, $replacements, $string);
?>

Example 6

Replacing several values


<?php//from w  w  w.j  a  v  a 2  s.  c  om
$patterns = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/','/^\s*{(\w+)}\s*=/');
$replace = array ('\3/\4/\1\2', '$\1 =');
echo preg_replace($patterns, $replace, '{startDate} = 2013-5-21');
?>

The code above generates the following result.

Example 7

This example strips excess whitespace from a string.


<?php//from  w w w  . java  2  s  .  co  m
$str = 'foo   o';
$str = preg_replace('/\s\s+/', ' ', $str);
echo $str;
?>

The code above generates the following result.

Example 8

Using the count parameter


<?php/*from w ww  .  ja va 2 s  .c om*/
$count = 0;

echo preg_replace(array('/\d/', '/\s/'), '*', 'Java 4 PHP', -1 , $count);
echo $count; //3
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Development »




Environment
Error
Hash
Include
Locale
Math
Network
Output
Reflection
PHP Regular Expressions