preg_match一些问题

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

以上例程会输出:

The bear black slow jumps over the lazy dog.

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

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

以上例程会输出:

The slow black bear jumps over the lazy dog.

==============================================================
<?php
$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
posted @ 2018-08-12 10:59  study_php_java_C++  阅读(126)  评论(0编辑  收藏  举报