preg_replace php

The preg_replace() function behaves like the search-and-replace operation in your text editor. It finds all occurrences of a pattern in a string and changes those occurrences to something else:

$new = preg_replace(pattern, replacement, subject [, limit ]);

The most common usage has all the argument strings except for the integer limit. The limit is the maximum number of occurrences of the pattern to replace (the default, and the behavior when a limit of −1 is passed, is all occurrences):

$better = preg_replace('/<.*?>/', '!', 'do <b>not</b> press the button');
// $better is 'do !not! press the button'

More Example of pre_replace in php

$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);
$string = 'The quick brown fox jumps 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);
$patterns = array ('/(19|20)(\d{2})-(\d{1,2})-(\d{1,2})/',
$replace = array ('\3/\4/\1\2', '$\1 =');
echo preg_replace($patterns, $replace, '{startDate} = 1999-5-27');

Leave a Comment