PHP7中PCRE增加了一個新的函數,那就是preg_replace_callback_array。
在此之前,PCRE中就已經有了preg_replace_callback,那這兩者之間又有什麼共同點和區別
首先複習一下preg_replace_callback的函數定義。
mixed preg_replace_callback ( mixed $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] )
其中,$pattern可以是string或array類型。
再來先看下方代碼:
<?php
$subject = 'hello world!';
$replaced = preg_replace_callback([
'#(hello)#',
'#(world)#',
], function ($matches) {
return strtoupper($matches[1]);
}, $subject);
echo $replaced;
// HELLO WORLD!
再看preg_replace_callback_array的函數定義:
mixed preg_replace_callback_array ( array $patterns_and_callbacks , mixed $subject [, int $limit = -1 [, int &$count ]] )
與preg_replace_callback對比,沒有了$pattern和$callback,而是將兩個結合成了一個associative的數組。
再看看示例代碼:
<?php
$subject = 'Hello World';
$replaced = preg_replace_callback_array([
'#(Hello)#' => function ($matches) {
return 'Good';
},
'#(World)#i' => function ($match) {
return 'day';
}
], $subject);
echo $replaced;
// OUTPUT
// Good day
可以看出,preg_replace_callback只能針對多個pattern的匹配模式作出同一種callback行爲。當然,可以在callback中實現不同的控制分支(switch/if),而preg_replace_callback_array則是通過傳遞pattern=>callback的associative對應關係,實現一對一的callback操作,更具清晰化。
總結:
相同點:
1)都是通過PCRE模式進行匹配,並實現替換
2)參數和返回值也基本相同,如subject爲數組時,返回值爲數組;subject爲字符串時,返回值爲字符串
不同點:
1)preg_replace_callback的pattern參數可以爲字符串或數字下標的PCRE模式數組;而preg_replace_callback_array的pattern只能爲keyValue的數組;
2)preg_replace_callback的callback會對pattern參數中所有的模式作相同的操作;而preg_replace_callback_array的pattern因爲定義了keyValue的方式,會使用相應的key對應的callback進行處理;
3)參數數量不同:preg_replace_callback爲5個參數,preg_replace_callback_array爲4個參數