» 网友学堂 » PHP教程 » preg_replace() 函数用法详解
preg_replace() 函数用法详解
作者:问天 发表时间:2007-3-16 17:16 阅读:3917次 在百度搜索相关内容

先举几个例子

一、日期转换
以下是代码:
<?php
$patterns = array("/(19│20\d{2})-(\d{1,2})-(\d{1,2})/", "/^\s*{(\w+)}\s*=/");
$replace = array("\\3/\\4/\\1", "$\\1 =");
print preg_replace($patterns, $replace, "{startDate} = 1969-6-19");
?>

输出结果:$startDate = 1969-6-19

二、分割字符
以下是代码:
<?
$a = "1100011111000010010000000";
echo preg_replace("/(\d{5})/","\${1}\n",$a);
?>

输出结果:
11000
11111
00001
00100
00000

三、重新排列字符串
以下是代码:
<?php
$string = "April 15, 2007";
$pattern = "/(\w+) (\d+), (\d+)/i";
$replacement = "\${1}1,\$3";
print preg_replace($pattern, $replacement, $string);
?>

输出结果:April1,2007
标注:preg_replace() 搞不清楚是想要一个 \\1 的逆向引用后面跟着一个数字 1 还是一个 \\11 的逆向引用。本例中的解决方法是使用 \${1}1

四、清除字符
以下是代码:

<?
$text = ">185<";
$pattern = "/(>)([1-9][0-9]*)(<)/";
print preg_replace ($pattern, '$2',$text);
?>
输出185

#Advertisement