substr_count()

1. 定义

该函数返回指定子字符串在字符串中出现的次数。

注:该函数不计算重叠的字符串。

2. 语法

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

3. 参数说明

参数 可选性 数据类型 描述
$haystack 必需 字符串 被搜索的源字符串
$needle 必需 字符串 要搜索的目标字符串
$offset 可选 整型 搜索开始的位置索引值,默认为0,从$haystack最左边开始搜索
$length 可选 整型 最大搜索长度($length + $offset的和不能超过$haystack的值)

4. 示例

<?php

// substr_count()
// 返回指定子字符串在字符串中出现的次数

$haystack = '极速教程是一个优秀的教程网站';
$needle = '教程';
$res = substr_count($haystack, $needle);
var_dump($res);// 输出:int(2)

// 如果要查找的字符串发生重叠现象
$haystack = '极速教程教程教程学习PHP入门';
$needle = '教程教程';
$res = substr_count($haystack, $needle);
var_dump($res);// 输出:int(1)

5. 延展阅读

  • count_chars():返回指定字符串中,每个字节值出现的次数数组
  • strpos():查找特定子字符串首次出现的位置索引值(从 0 开始)
  • substr():返回从某位置开始、特定长度的子字符串
  • strstr():返回特定索引或特定子字符串首次出现的位置到字符串结尾的部分