首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[函数]substr_count()函数—用法及示例

发布于 2025-05-08 19:35:43
0
9

函数名:substr_count()

适用版本:PHP 4 >= 4.0.5, PHP 5, PHP 7

函数描述:substr_count() 函数用于计算字符串中一个子字符串出现的次数。

语法:int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )

参数:

  • $haystack:要在其中搜索的字符串。
  • $needle:要搜索的子字符串。
  • $offset(可选):从字符串的第 offset 个字符开始搜索,默认为 0。
  • $length(可选):指定要搜索的字符数,默认搜索整个字符串。

返回值:返回子字符串在字符串中出现的次数,如果没有出现则返回 0。

示例 1:

$str = 'Hello, World!';
$count = substr_count($str, 'o');
echo $count; // 输出 2

示例 2:

$str = 'abcdeabcdeabcde';
$count = substr_count($str, 'abc', 2, 6);
echo $count; // 输出 2

上述示例中,substr_count() 函数在示例 1 中计算了字符串 "Hello, World!" 中字母 "o" 的出现次数,结果为 2。在示例 2 中,它计算了字符串 "abcdeabcdeabcde" 中从索引位置 2 开始的 6 个字符中子字符串 "abc" 的出现次数,结果同样为 2。

评论
一个月内的热帖推荐
啊龙
Lv.1普通用户

8926

帖子

29

小组

2863

积分

站长交流