当前位置: 首页> 函数类别大全> mb_substr_count

mb_substr_count

计算子字符串出现次数
名称:mb_substr_count
分类:多字节字符串
所属语言:php
一句话介绍:计算子字符串出现次数

mb_substr_count 函数

适用PHP版本

PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8

函数说明

mb_substr_count 函数用于统计在字符串中某个子字符串出现的次数。此函数是多字节字符串函数(mbstring)的一部分,专门用于处理多字节字符编码(如UTF-8)。

函数语法

int mb_substr_count ( string $haystack , string $needle [, string $encoding = mb_internal_encoding() ] )

参数

  • $haystack:输入的目标字符串。
  • $needle:要查找的子字符串。
  • $encoding(可选):指定字符编码,默认使用当前的内部编码。

返回值

返回子字符串出现的次数。如果没有找到子字符串,则返回0。

示例

<?php
$str = "Hello world, hello PHP!";
$needle = "hello";
$count = mb_substr_count($str, $needle, "UTF-8");
echo $count;  // 输出 2
?>

示例代码的说明

在示例中,我们定义了一个包含 "Hello world, hello PHP!" 的字符串 `$str`,并使用 `mb_substr_count()` 来统计 "hello" 这个子字符串在其中出现的次数。结果输出2,因为"hello"在字符串中出现了两次(注意大小写)。

同类函数
热门文章