Hàm preg_replace_callback_array() trong PHP
Ví dụ
Hiển thị có bao nhiêu chữ cái hoặc chữ số được tìm thấy trong mỗi từ trong một câu:
<?php
function countLetters($matches) {
return $matches[0] . '[' .
strlen($matches[0]) . 'letter]';
}
function countDigits($matches) {
return $matches[0] . '[' . strlen($matches[0]) . 'digit]';
}
$input
= "There are 365 days in a year.";
$patterns = [
'/\b[a-z]+\b/i' =>
'countLetters',
'/\b[0-9]+\b/' => 'countDigits'
];
$result =
preg_replace_callback_array($patterns, $input);
echo $result;
?>
Hãy tự mình thử »Định nghĩa và cách sử dụng
Hàm preg_replace_callback_array()
trả về một chuỗi hoặc một mảng các chuỗi trong đó các kết quả khớp của một tập hợp biểu thức chính quy được thay thế bằng giá trị trả về của hàm gọi lại.
Lưu ý: Đối với mỗi chuỗi, hàm sẽ đánh giá các mẫu theo thứ tự chúng được đưa ra. Kết quả của việc đánh giá mẫu đầu tiên trên chuỗi được sử dụng làm chuỗi đầu vào cho mẫu thứ hai, v.v. Điều này có thể dẫn đến hành vi không mong muốn.
Cú pháp
preg_replace_callback_array( patterns, input, limit, count )
Giá trị tham số
Parameter | Description |
---|---|
pattern | Required. An associative array which associates regular
expression patterns to callback functions. The callback functions have one parameter which is 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: | 7+ |
Thêm ví dụ
Ví dụ
Ví dụ này minh họa những tác động tiềm tàng không mong muốn của các mẫu được đánh giá theo trình tự. Đầu tiên, phép thay thế countLetters thêm "[4letter]" vào "ngày" và sau khi việc thay thế đó được thực hiện, phép thay thế countDigits sẽ tìm thấy "4" trong "4letter" và thêm "[1digit]" vào đó:
<?php
function countLetters($matches) {
return $matches[0] . '[' .
strlen($matches[0]) . 'letter]';
}
function countDigits($matches) {
return $matches[0] . '[' . strlen($matches[0]) . 'digit]';
}
$input
= "365 days";
$patterns = [
'/[a-z]+/i' => 'countLetters',
'/[0-9]+/' => 'countDigits'
];
$result =
preg_replace_callback_array($patterns, $input);
echo $result;
?>
Hãy tự mình thử »❮ Tham khảo RegExp PHP