preg_replace_callback

preg_replace_callback — 执行一个正则表达式搜索并且使用一个回调进行替换

/* 一个unix样式的命令行过滤器,用于将段落开始部分的大写字母转换为小写。 /
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
$line = fgets($fp);
$line = preg_replace_callback(
'/

\s\w/',
function ($matches) {
return strtolower($matches[0]);
},
$line
);
echo $line;
}
fclose($fp);
?>
while(!feof($fp)){
$line = fgets($fp);
$line = preg_replace_callback('/\s.*\w/',function($matches){
return strtolower($matches[0]);
},$line);
echo $line;
}

$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";

// 回调函数
function next_year($matches) {
// 通常:$matches[0] 是完整的匹配项
// $matches[1] 是第一个括号中的子模式的匹配项
// 以此类推
return $matches[1].($matches[2]+1);
}

echo preg_replace_callback(
"/(\d{2}/\d{2}/)(\d{4})/",
"next_year",
$text);

// 结果为:
// April fools day is 04/01/2003
// Last christmas was 12/24/2002
?>

你可能感兴趣的:(preg_replace_callback)