PHP preg_filter()ฟังก์ชัน
ตัวอย่าง
ตัดตัวเลขในวงเล็บในรายการสตริง:
<?php
$input = [
"It is 5 o'clock",
"40 days",
"No
numbers here",
"In the year 2000"
];
$result =
preg_filter('/[0-9]+/', '($0)', $input);
print_r($result);
?>
ความหมายและการใช้งาน
ฟังก์ชันpreg_filter()
ส่งคืนสตริงหรืออาร์เรย์ของสตริงที่ตรงกับรูปแบบถูกแทนที่ด้วยสตริงการแทนที่
ถ้าอินพุตเป็นอาร์เรย์ ฟังก์ชันนี้จะคืนค่าอาร์เรย์ หากอินพุตเป็นสตริง ฟังก์ชันนี้จะส่งคืนสตริง
ฟังก์ชันนี้คล้ายpreg_replace()
กับความแตกต่างอย่างหนึ่ง: เมื่อไม่พบการจับคู่สำหรับรูปแบบในสตริงอินพุต สตริงจะไม่ถูกใช้ในค่าที่ส่งกลับ ในสถานการณ์สมมตินี้ หากอินพุตเป็นสตริงแทนที่จะเป็นอาร์เรย์ ฟังก์ชันจะคืนค่าnull
สตริงการแทนที่อาจมี backreferences ในรูปแบบ \n หรือ $n โดยที่nคือดัชนีของกลุ่มในรูปแบบ ในสตริงที่ส่งคืน อินสแตนซ์ของ \n และ $n จะถูกแทนที่ด้วยสตริงย่อยที่ตรงกับกลุ่ม หรือหากใช้ \0 หรือ $0 โดยนิพจน์ทั้งหมด
ไวยากรณ์
preg_filter(pattern, replacement, input, limit, count)
ค่าพารามิเตอร์
Parameter | Description |
---|---|
pattern | Required. Contains a regular expression indicating what to search for |
replacement | Required. A string which will replace the matched patterns. It may contain backreferences |
input | Required. A string or array of strings in which the replacements are being performed |
limit | Optional. Defaults to -1, meaning unlimited. Sets a limit to how many replacements can be done in each string |
count | Optional. After the function has executed, this variable will contain a number indicating how many replacements were performed |
รายละเอียดทางเทคนิค
คืนมูลค่า: | ส่งกลับอาร์เรย์ของสตริงที่ถูกแทนที่หากอินพุตเป็นอาร์เรย์ สตริงที่มีการแทนที่หากอินพุตเป็นสตริงหรือ null หากอินพุตเป็นสตริงและไม่พบรายการที่ตรงกัน |
---|---|
รุ่น PHP: | 5.3.0 |
❮ การอ้างอิง PHP RegExp