首先我们来一个示例,如何把下面这段字符串中所有年份增加一年?
$text = "April fools day is 04/01/2002,Last christmas was 12/24/2001,April fools day is 04/01/2002, Last christmas was 12/24/2001, April fools day is 04/01/2002, Last christmas was 12/24/2001, April fools day is 04/01/2002, Last christmas was 12/24/2001, April fools day is 04/01/2002, Last christmas was 12/24/2001, April fools day is 04/01/2002, Last christmas was 12/24/2001, April fools day is 04/01/2002, Last christmas was 12/24/2001, April fools day is 04/01/2002, Last christmas was 12/24/2001, April fools day is 04/01/2002, Last christmas was 12/24/2001, April fools day is 04/01/2002, Last christmas was 12/24/2001, April fools day is 04/01/2002, Last christmas was 12/24/2001" ,如何将这个字符串变量中的 所有年份增加一年?
$str = preg_replace_callback("|(\d{2}/\d{2}/)(\d{2})|",function($matches){ return $matches[1].($matches[2] + 1) },$text);
意思是,将$text中满足表达式"|(\d{2}/\d{2}/)(\d{4})|" 的内容放进第二参数闭包函数中并进行运算,闭包函数的参数就是每次满足正则匹配的字符串数组.从|(\d{2}/\d{2}/)(\d{4})| 中可以看出 表达式 有 两个括号,则 匿名函数将会传入满足正则表达式的数组,如下:
Array | |
( | |
[0] => 04/01/2002 | |
[1] => 04/01/ | |
[2] => 2002 | |
) |
Array | |
( | |
[0] => 12/24/2001 | |
[1] => 12/24/ | |
[2] => 2001 | |
) |
Array | |
( | |
[0] => 04/01/2002 | |
[1] => 04/01/ | |
[2] => 2002 | |
) |
.
.(此处省略多个匹配项)
此时我们可以在匿名函数返回想要的内容 即 $matches[1].($matches[2]+1) 就是需要得到的正则替换.
Loader::parseName 中 有一段代码如下:
$name = preg_replace_callback('/_([a-zA-Z])/', function ($match) { return strtoupper($match[1]); }, $name);
如何理解这一段代码呢??
我们可以参照前面的例子,假如 $text = "April fools day is very_good , my name is qin_shixian";
字符串中满足 "/_[a-zA-Z]/" 的有 "_g" 和 "_s" ,那么这两个字符串会 转化为大写,并且没有带_,
即返回 内容 $name = "April fools day is veryGood , my name is qinShixian";
可见这段代码是将带有下划线的字符串转化为 大写,并去掉下划线