Hàm preg_replace_callback_array () trong PHP
Thí dụ
Cho biết 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;
?>
Đị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 chuỗi trong đó các trận đấu của một tập hợp các biểu thức chính quy được thay thế bằng giá trị trả về của một hàm gọi lại.
Lưu ý: Đối với mỗi chuỗi, hàm đánh giá các mẫu theo thứ tự mà chúng được đưa ra. Kết quả đá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ả lại: | Trả về một chuỗi hoặc một mảng chuỗi kết quả từ việc áp dụng các thay thế cho chuỗi hoặc chuỗi đầu vào |
---|---|
Phiên bản PHP: | 7+ |
Các ví dụ khác
Thí dụ
Ví dụ này minh họa các tác động không mong muốn có thể xảy ra 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 "days" và sau khi thực hiện thay thế đó, phép thay thế countDigits sẽ tìm "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;
?>
❮ Tham khảo PHP RegExp