PHP preg_match()関数
例
正規表現を使用して、文字列内の「w3schools」で大文字と小文字を区別しない検索を実行します。
<?php
$str = "Visit W3Schools";
$pattern = "/w3schools/i";
echo
preg_match($pattern, $str);
?>
定義と使用法
このpreg_match()
関数は、文字列で一致が見つかったかどうかを返します。
構文
preg_match(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:
|
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 |
技術的な詳細
戻り値: | 一致が見つかった場合は1を返し、一致が見つからなかった場合は0を返し、エラーが発生した場合はfalseを返します。 |
---|---|
PHPバージョン: | 4歳以上 |
変更ログ: | PHP7.2-PREG_UNMATCHED_AS_NULLフラグを追加しましたPHP5.3.6- オフセットが入力の長さよりも長い場合、関数はfalseを返しますPHP 5.2.2- 名前付きサブパターンは(? 'name')および(?<name>)を使用できます前の(?P <name>)に加えて構文 |
その他の例
例
PREG_OFFSET_CAPTUREを使用して、一致が見つかった入力文字列内の位置を見つけます。
<?php
$str = "Welcome to W3Schools";
$pattern = "/w3schools/i";
preg_match($pattern, $str, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
❮PHPRegExpリファレンス