PHP 使用preg_replace()对字符进行替换处理

Example #1 使用后向引用紧跟数值原文


$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);

以上例程会输出:

April1,2003


Example #2 preg_replace()中使用基于索引的数组


$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);

以上例程会输出:

The bear black slow jumped over the lazy dog.


对模式和替换内容按key进行排序我们可以得到期望的结果。


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


以上例程会输出:

The slow black bear jumped over the lazy dog.

 

Example #3 替换一些值

 

$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} = 1999-5-27');


以上例程会输出:

$startDate = 5/27/1999

 

Example #4 剥离空白字符

这个例子剥离多余的空白字符

$str = 'foo   o';
$str = preg_replace('/\s\s+/', ' ', $str);
// 将会改变为'foo o'
echo $str;

 

Example #5 使用参数count

$count = 0;

echo preg_replace(array('/\d/', '/\s/'), '*', 'xp 4 to', -1 , $count);
echo $count; //3

以上例程会输出:

xp***to
3

posted @ 2022-09-15 13:40  Rukh  阅读(242)  评论(0编辑  收藏  举报