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);
}
?>
自己動手試一試 »
定義和用法
The preg_match_all()
function returns the number of matches of a pattern that were found in a string and populates a variable with the matches that were found。
語法
preg_match_all(pattern, input, matches, flags, offset)
引數值
引數 | 描述 |
---|---|
pattern | 必需。包含一個正則表示式,指示要搜尋的內容 |
input | 必需。要在其中執行搜尋的字串 |
matches | 可選。此引數中的變數將用一個包含所有找到的匹配項的陣列進行填充 |
flags | 可選。一組選項,用於更改匹配項陣列的結構。 可以選擇以下結構之一
|
offset | 可選。預設為 0。指示從字串的哪個位置開始搜尋。preg_match() 函式將不會找到在該引數給定的位置之前的匹配項 |
技術詳情
返回值 | 返回找到的匹配項的數量,如果發生錯誤則返回 false |
---|---|
PHP 版本 | 4+ |
更新日誌 | PHP 7.2 - 添加了 PREG_UNMATCHED_AS_NULL 標誌 PHP 5.4 - matches 引數變得可選 PHP 5.3.6 - 當 offset 長於 input 的長度時,函式返回 false PHP 5.2.2 - 除了之前的 (?P<name>) 語法外,命名子模式還可以使用 (?'name') 和 (? <name>) 語法 |
更多示例
示例
使用 PREG_PATTERN_ORDER 設定 matches 陣列的結構。在此示例中,matches 陣列中的每個元素都包含正則表示式一個分組的所有匹配項。
<?php
$str = "abc ABC";
$pattern = "/((a)b)(c)/i";
if(preg_match_all($pattern, $str, $matches, PREG_PATTERN_ORDER)) {
print_r($matches);
}
?>
自己動手試一試 »
❮ PHP 正則表示式參考