首頁 >後端開發 >php教程 >如何使用「preg_match_all()」在 PHP 中尋找字串的所有出現位置?

如何使用「preg_match_all()」在 PHP 中尋找字串的所有出現位置?

Susan Sarandon
Susan Sarandon原創
2024-11-29 00:24:10797瀏覽

How Can I Find All Occurrences of a String in PHP Using `preg_match_all()`?

在PHP 中使用preg_match_all 查找多次出現

問題:

如何利用PHP的preg_match辨識給定字串中特定字串的多次出現text?

範例:

假設我們要判斷字串「/brown Fox gone [0-9]/」在下面的內容中是否出現了兩次段落:

$string = "/brown fox jumped [0-9]/";

$paragraph = "The brown fox jumped 1 time over the fence. The green fox did not. Then the brown fox jumped 2 times over the fence.";

答案:

雖然preg_match 可以偵測字串的第一次出現,但要定位多次出現,我們必須使用preg_match_all() 函數。使用 preg_match_all() 的修正程式碼如下:

if (preg_match_all($string, $paragraph, $matches)) {
    echo count($matches[0]) . " matches found";
} else {
    echo "match NOT found";
}

在此程式碼中,$matches 是一個包含找到的所有符合項目的陣列。 count($matches[0]) 表達式傳回符合項的數量。

輸出:

此程式碼將產生以下輸出,因為給定的字串在該段落:

2 matches found

以上是如何使用「preg_match_all()」在 PHP 中尋找字串的所有出現位置?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn