PHP preg_replace_callback_array()関数
例
文中の各単語に含まれる文字または数字の数を表示します。
<?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;
?>
定義と使用法
このpreg_replace_callback_array()
関数は、一連の正規表現の一致がコールバック関数の戻り値に置き換えられた文字列または文字列の配列を返します。
注:関数は、文字列ごとに、指定された順序でパターンを評価します。文字列の最初のパターンを評価した結果は、2番目のパターンの入力文字列として使用されます。これにより、予期しない動作が発生する可能性があります。
構文
preg_replace_callback_array(patterns, input, limit, count)
パラメータ値
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 |
技術的な詳細
戻り値: | 入力文字列に置換を適用した結果の文字列または文字列の配列を返します |
---|---|
PHPバージョン: | 7歳以上 |
その他の例
例
この例は、順番に評価されているパターンの潜在的に予期しない影響を示しています。まず、countLetters置換は、「日」に「[4letter]」を追加し、その置換が実行された後、countDigits置換は、「4letter」内の「4」を検出し、それに「[1digit]」を追加します。
<?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;
?>
❮PHPRegExpリファレンス