Hàm PHP preg_replace_callback()
Ví dụ
Đếm tất cả các chữ cái trong câu:
<?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;
?>
Hãy tự mình thử »Định nghĩa và cách sử dụng
Hàm preg_replace_callback()
, được cung cấp một biểu thức và một lệnh gọi lại, trả về một chuỗi trong đó tất cả các kết quả khớp của biểu thức được thay thế bằng chuỗi con do hàm gọi lại trả về.
Cú pháp
preg_replace_callback( pattern, callback, input, limit, count )
Giá trị tham số
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 |
Chi tiết kỹ thuật
Giá trị trả về: | Trả về một chuỗi hoặc một mảng các chuỗi do việc áp dụng các thay thế cho chuỗi hoặc các chuỗi đầu vào. |
---|---|
Phiên bản PHP: | 4.0.5+ |
Nhật ký thay đổi: | PHP 5.1.0 - Tham số đếm đã được thêm vào |
❮ Tham khảo RegExp PHP