mb_ereg_replace_callback

(PHP 5 >= 5.4.1, PHP 7, PHP 8)

mb_ereg_replace_callbackマルチバイト文字列にコールバック関数を用いた正規表現による置換を行う

説明

mb_ereg_replace_callback(
    string $pattern,
    callable $callback,
    string $string,
    ?string $options = null
): string|false|null

stringから patternにマッチする文字列を検索し、 一致した文字列をcallback関数の出力で置換します。

この関数の動作はmb_ereg_replace()とほぼ同じですが、 replacementパラメータの代わりに callbackを指定するところが異なります。

パラメータ

pattern

正規表現パターン。

patternではマルチバイト文字列を使用可能です。

callback

コールバック関数で、 string文字列で一致した要素を配列で 指定してコールされます。 このコールバック関数は、置換した文字列を返す必要があります。

しばしば、 mb_ereg_replace_callback()callback関数が必要となるのは一度だけである 場合があります。 この場合、 mb_ereg_replace_callback()をコールする際の コールバックに 匿名関数 を使用することができます。 このようにすることで、 コールに関する全ての情報を一つの場所に集約し、 他のどこでも使用されないコールバック関数の名前を 関数の名前空間にばらまかないですみます。

string

チェックされるstring

options

検索オプション。説明は、mb_regex_set_options() を参照ください。

戻り値

成功した際に置換後の文字列、 そうでない場合はエラー時に false を返します。 string が現在のエンコーディングに照らして不正な場合は、null を返します。

変更履歴

バージョン 説明
8.0.0 options は、nullable になりました。
7.1.0 この関数は、現在のエンコーディングに照らして string が正しいかをチェックするようになりました。

例1 mb_ereg_replace_callback() の例

<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// the callback function
function next_year($matches)
{
// as usual: $matches[0] is the complete match
// $matches[1] the match for the first subpattern
// enclosed in '(...)' and so on
return $matches[1].($matches[2]+1);
}
echo
mb_ereg_replace_callback(
"(\d{2}/\d{2}/)(\d{4})",
"next_year",
$text);

?>

上の例の出力は以下となります。

April fools day is 04/01/2003
Last christmas was 12/24/2002

例2 匿名関数を使用したmb_ereg_replace_callback()の例

<?php
// this text was used in 2002
// we want to get this up to date for 2003
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";

echo
mb_ereg_replace_callback(
"(\d{2}/\d{2}/)(\d{4})",
function (
$matches) {
return
$matches[1].($matches[2]+1);
},
$text);
?>

注意

注意:

内部エンコーディングあるいは mb_regex_encoding() で指定した文字エンコーディングを、 この関数の文字エンコーディングとして使用します。

参考

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top