欢迎访问宙启技术站
智能推送

PHP中的substr_count()函数:用法及示例。

发布时间:2023-06-07 07:25:37

substr_count()是PHP内置函数之一,用于计算一个字符串中另一个字符串出现的次数。它的语法如下:

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

其中,$haystack是要搜索的长字符串,$needle是要查找的子字符串;$offset是开始计数的位置,$length是要搜索的字符数。

下面是一些常见的用法和示例:

1. 查找单个字符在字符串中出现的次数:

$mystr = "Hello World";

echo substr_count($mystr, "o");

// 输出结果: 2

这里$mystr是要搜索的字符串,"o"是要查找的字符。

2. 查找多个字符在字符串中出现的次数:

$mystr = "Be happy and happy";

echo substr_count($mystr, "e");

// 输出结果: 2

3. 查找子字符串在字符串中出现的次数:

$mystr = "PHP is a popular programming language. PHP is widely used.";

echo substr_count($mystr, "PHP");

// 输出结果: 2

4. 查找子字符串在字符串中出现的次数时,指定搜索的起始位置和搜索的字符数:

$mystr = "PHP is a popular programming language. PHP is widely used.";

echo substr_count($mystr, "PHP", 10, 20);

// 输出结果: 1

这里指定从第10个字符开始搜索,一共搜索20个字符,即从"programming"开始搜索。

注意:substr_count()函数区分大小写。

5. 查找子字符串在字符串中出现的次数时,忽略大小写:

$mystr = "PHP is a popular programming language. PHP is widely used.";

echo substr_count(strtolower($mystr), "php");

// 输出结果: 2

将$mystr转换为小写字符串,再搜索"php"即可。

6. 查找子字符串在字符串中出现的次数时,同时指定起始位置和忽略大小写:

$mystr = "PHP is a popular programming language. PHP is widely used.";

echo substr_count(substr(strtolower($mystr), 10), "php");

// 输出结果: 1

这里先将$string转为小写,并从第10个字符开始搜索,再搜索"php"即可。

总之,substr_count()函数是一个非常实用的字符串函数,在我们的PHP编程过程中可以经常使用。