PHP preg_match_all()関数
例
文字列内の「ain」のすべての出現を検索します。
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern =
"/ain/i";
if(preg_match_all($pattern, $str, $matches)) {
print_r($matches);
}
?>
定義と使用法
このpreg_match_all()
関数は、文字列で見つかったパターンの一致数を返し、見つかった一致を変数に入力します。
構文
preg_match_all(pattern, input, matches, flags, offset)
パラメータ値
Parameter | Description |
---|---|
pattern | Required. Contains a regular expression indicating what to search for |
input | Required. The string in which the search will be performed |
matches | Optional. The variable used in this parameter will be populated with an array containing all of the matches that were found |
flags | Optional. A set of options that change how the matches array is structured. One of the following structures may be selected:
|
offset | Optional. Defaults to 0. Indicates how far into the string to begin searching. The preg_match() function will not find matches that occur before the position given in this parameter |
技術的な詳細
戻り値: | 見つかった一致の数を返します。エラーが発生した場合はfalseを返します |
---|---|
PHPバージョン: | 4歳以上 |
変更ログ: | PHP7.2-PREG_UNMATCHED_AS_NULLフラグを追加しましたPHP5.4 -matchesパラメーターがオプションになりましたPHP5.3.6- オフセットが入力の長さよりも長い場合、関数はfalseを返しますPHP 5.2.2- 名前付きサブパターンは(? 'name'前の(?P <name>)に加えて)および(?<name>)構文 |
その他の例
例
PREG_PATTERN_ORDERを使用して、matches配列の構造を設定します。この例では、matches配列の各要素に、正規表現のグループ化の1つに対するすべての一致が含まれています。
<?php
$str = "abc ABC";
$pattern = "/((a)b)(c)/i";
if(preg_match_all($pattern,
$str, $matches, PREG_PATTERN_ORDER)) {
print_r($matches);
}
?>
❮PHPRegExpリファレンス