此函數在字符串中搜索模式,如果模式存在,則返回true,否則返回false。通常,搜索從主題字符串的開頭開始。可選參數offset用於指定從何處開始搜索的位置。
用法:
int preg_match( $pattern, $input, $matches, $flags, $offset )
參數:該函數接受上述和以下所述的五個參數:
- pattern:此參數以字符串形式保存要搜索的模式。
- input:此參數保存輸入字符串。
- matches:如果存在匹配項,則它包含搜索結果。 $matches [0]將包含與完整模式匹配的文本,$matches [1]將包含與第一個捕獲的帶括號的子模式匹配的文本,依此類推。
- flags:這些標誌可以是以下標誌:
- PREG_OFFSET_CAPTURE:如果傳遞了此標誌,則對於每個匹配項,將返回附加字符串偏移量。
- PREG_UNMATCHED_AS_NULL:如果傳遞了此標誌,則不匹配的子模式將報告為NULL;否則,報告為NULL。否則,它們報告為空字符串。
- offset:通常,搜索從輸入字符串的開頭開始。此可選參數offset用於指定從哪裏開始搜索的位置(以字節為單位)。
返回值:如果模式存在,則返回true,否則返回false。
以下示例說明了PHP中的preg_match()函數:
範例1:本示例接受PREG_OFFSET_CAPTURE標誌。
<?php
// Declare a variable and initialize it
$geeks = 'GeeksforGeeks';
// Use preg_match() function to check match
preg_match('/(Geeks)(for)(Geeks)/', $geeks, $matches, PREG_OFFSET_CAPTURE);
// Display matches result
print_r($matches);
?>
輸出:
Array ( [0] => Array ( [0] => GeeksforGeeks [1] => 0 ) [1] => Array ( [0] => Geeks [1] => 0 ) [2] => Array ( [0] => for [1] => 5 ) [3] => Array ( [0] => Geeks [1] => 8 ) )
範例2:
<?php
// Declare a variable and initialize it
$gfg = "GFG is the best Platform.";
// case-Insensitive search for the word "GFG"
if (preg_match("/\bGFG\b/i", $gfg, $match))
echo "Matched!";
else
echo "not matched";
?>
輸出:
Matched!
參考: http://php.net/manual/en/function.preg-match.php
相關用法
- d3.js d3.set.has()用法及代碼示例
- p5.js hex()用法及代碼示例
- p5.js pow()用法及代碼示例
- CSS var()用法及代碼示例
- PHP pow( )用法及代碼示例
- p5.js sq()用法及代碼示例
- PHP pi( )用法及代碼示例
- PHP Ds\Map get()用法及代碼示例
- p5.js max()用法及代碼示例
- p5.js int()用法及代碼示例
- PHP each()用法及代碼示例
- d3.js d3.map.has()用法及代碼示例
注:本文由純淨天空篩選整理自PranchalKatiyar大神的英文原創作品 PHP | preg_match() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。