ฟังก์ชัน Preg_replace_callback_array() ใน PHP 7 แสดงนิพจน์ปกติและแทนที่การใช้ callbacks ฟังก์ชันนี้คืนค่าสตริงหรืออาร์เรย์ของสตริงเพื่อจับคู่ชุดของนิพจน์ปกติและแทนที่พวกเขาโดยใช้ฟังก์ชัน callback
รูปแบบ (Syntax)
preg_replace_callback_array(patterns, input, limit, count)
ค่าพารามิเตอร์:
- pattern - ต้องการ associative array เพื่อเชื่อมโยง regular expression patterns กับ callback functions
- input/subject - ต้องการอาร์เรย์ของสตริงเพื่อทำการแทนที่
- limit - เป็น optional -1 ใช้สำหรับ default หมายถึง unlimited ตั้งขีดจำกัดจำนวนการแทนที่ในแต่ละสตริง
- count - เป็น optional เช่นเดียวกับ limit ตัวแปรนี้จะมีจำนวน แสดงว่ามีการแทนที่กี่ครั้งหลังจากฟังก์ชัน execute
- flags - อาจเป็นการรวมของ preg_offset_capture และ preg_unmatched_as_null flags ซึ่งส่งผลต่อรูปแบบของ matched array
- Return Values - preg_replace_callback_array() คืนค่าสตริงหรืออาร์เรย์ของสตริง หากพบข้อผิดพลาด จะคืนค่า null หากพบการจับคู่ subject ใหม่จะถูกคืน มิฉะนั้น subject จะถูกคืนค่า unchanged
Preg_replace_callback_array() : ตัวอย่าง
<html> <head> <title> PHP 7 Feature tutorialpoint:</title> </head> <body> <?php
$subject = 'AaaaaaaBbbbCccc';
preg_replace_callback_array (
[
'~[a]+~i' => function ($match) {
echo strlen($match[0]), ' number of "a" found', PHP_EOL;
},
'~[b]+~i' => function ($match) {
echo strlen($match[0]), ' number of "b" found', PHP_EOL;
},
'~[c]+~i' => function ($match) {
echo strlen($match[0]), ' number of "c" found', PHP_EOL;
}
],
$subject
);
?> </body> </html>
ผลลัพธ์
ผลลัพธ์สำหรับโค้ดโปรแกรมด้านบนคือ -
7 number of "a" found 4 number of "b" found 5 number of "c" found