PHP – 如何使用 mb_substr_count() 統計子字串的個數?


在 PHP 中,我們可以使用函式 **mb_substr_count()** 來統計給定字串中子字串的總數。

語法

int mb_substr_count(str $haystack, str $needle, str $encoding)

引數

**mb_substr_count()** 接受三個引數:**$haystack**、**$needle** 和 **$encoding**。

  • **$haystack**− 此引數將檢查字串。

  • **$needle**− 此引數將用於告知從給定的總字串中找到的子字串。

  • **$encoding**− 此引數是字元編碼。如果它不存在或為空,則將使用內部字元編碼值。

返回值

這將返回子字串 needle 在字串 haystack 中出現的次數。

示例

 線上演示

<?php
   // mb_substr_count function is used
   $string= mb_substr_count("This is a test", "is");
   echo "$string";
?>

輸出

2

更新於: 2021-08-23

154 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.