PHP preg_replace_callback()ฟังก์ชั่น
ตัวอย่าง
นับตัวอักษรในทุกคำในประโยค:
<?php
function countLetters($matches) {
return $matches[0] . '(' .
strlen($matches[0]) . ')';
}
$input = "Welcome to W3Schools.com!";
$pattern = '/[a-z0-9\.]+/i';
$result = preg_replace_callback($pattern,
'countLetters', $input);
echo $result;
?>
ความหมายและการใช้งาน
ฟังก์ชันpreg_replace_callback()
กำหนดนิพจน์และเรียกกลับ ส่งคืนสตริงที่ตรงกันทั้งหมดของนิพจน์จะถูกแทนที่ด้วยสตริงย่อยที่ส่งคืนโดยฟังก์ชันเรียกกลับ
ไวยากรณ์
preg_replace_callback(pattern, callback, input, limit, count)
ค่าพารามิเตอร์
Parameter | Description |
---|---|
pattern | Required. A regular expression or array of regular expressions indicating what to search for |
replacements | Required. A callback function which returns the replacement. The callback function has one parameter containing an array of matches. The first element in the array contains the match for the whole expression while the remaining elements have matches for each of the groups in the expression. |
input | Required. The string or array of strings in which 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 |
รายละเอียดทางเทคนิค
คืนมูลค่า: | ส่งกลับสตริงหรืออาร์เรย์ของสตริงที่เกิดจากการใช้การแทนที่กับสตริงอินพุตหรือสตริง |
---|---|
รุ่น PHP: | 4.0.5+ |
บันทึกการเปลี่ยนแปลง: | PHP 5.1.0 - เพิ่มพารามิเตอร์การนับแล้ว |
❮ การอ้างอิง PHP RegExp