<?
if (preg_match ("/(\bweb\b)\s(\d)/i", "PHP is the web 45 scripting web 34 language of choice.",$match)) {
print "A match was found.";
print_r($match);
} else {
print "A match was not found.";
}
?>
<?php
preg_match_all ("|<[^>]+>(.*)</[^>]+>|U",
"<b>example: </b><div align=left>this is a test</div>",
$out, PREG_SET_ORDER);
print $out[0][0].", ".$out[0][1]."\n";
print $out[1][0].", ".$out[1][1]."\n";
?>
本例将输出:
<b>example: </b>, example:
<div align=left>this is a test</div>, this is a test
本函数的行为几乎和 preg_replace() 一样,除了不是提供一个 replacement 参数,而是指定一个 callback 函数。该函数将以目标字符串中的匹配数组作为输入参数,并返回用于替换的字符串。
例子 1. preg_replace_callback() 例子
<?php
// 此文本是用于 2002 年的,
// 现在想使其能用于 2003 年
$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
?>
You'll often need the callback function for a preg_replace_callback() in just one place. In this case you can use create_function() to declare an anonymous function as callback within the call to preg_replace_callback(). By doing it this way you have all information for the call in one place and do not clutter the function namespace with a callback functions name not used anywhere else.
对于使用 preg_replace_callback()函数的朋友来说,你应该回需要callback函数(否则用他干嘛,直接用preg_replace不是更好),不过也经常只是用一处。既然这样你可以用create_function()来声明一个匿名函数作为 preg_replace_callback()的回调函数。这样,我们即满足了声明信息的需要,有不致因这个不会再用到的函数名而混乱。
例子 2. preg_replace_callback() 和 create_function()
<?php
/* 一个 UNIX 风格的命令行过滤器,将每个段落开头的
* 大写字母转换成小写字母 */
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
$line = fgets($fp);
$line = preg_replace_callback(
'|<p>\s*\w|',
create_function(
// 这里使用单引号很关键,
// 否则就把所有的 $ 换成 \$
'$matches',
'return strtolower($matches[0]);'
),
$line
);
echo $line;
}
fclose($fp);
?>