PHP中substr_count()函数用法详解|计算字串出现的次数

2023-09-09 54 阅读 0评论
PHP中的substr_count()函数是用于计算字符串中子字符串出现的次数。

substr_count()函数语法

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

其中,$haystack是要搜索的字符串,$needle是要搜索的子字符串,$offset是可选的起始位置,默认为0,$length是可选的搜索长度,默认为整个字符串的长度。
该函数返回子字符串在字符串中出现的次数,如果子字符串未出现,则返回0。

substr_count()函数的用法

计算整个字符串中子字符串的出现次数:

首先,我们可以使用substr_count()函数来计算整个字符串中子字符串的出现次数。例如:

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

在上面的例子中,$str是要搜索的字符串,"Hello"是要搜索的子字符串,substr_count()函数返回2,因为"Hello"在字符串中出现了两次。

指定起始位置和搜索长度:

substr_count()函数还可以接受两个可选参数:$offset$length$offset表示要开始搜索的位置,$length表示要搜索的长度。 例如,我们可以指定搜索字符串的起始位置为7,长度为10,来计算子字符串的出现次数:

$str = "Hello, World! Hello, PHP!";
$count = substr_count($str"Hello", 7, 10);
echo $count; // 输出1

在上面的例子中,$str是要搜索的字符串,"Hello"是要搜索的子字符串,$offset为7,$length为10。substr_count()函数返回1,因为从位置7开始,在长度为10的子字符串中,"Hello"只出现了一次。

大小写敏感和不敏感的搜索:

substr_count()函数默认是大小写敏感的,也就是说,它区分大小写。例如:

$str = "Hello, World! hello, PHP!";
$count = substr_count($str"hello");
echo $count; // 输出1

在上面的例子中,$str是要搜索的字符串,"hello"是要搜索的子字符串,substr_count()函数返回1,因为它只匹配到了一个大小写一致的子字符串。
如果我们想要进行大小写不敏感的搜索,可以将子字符串和要搜索的字符串都转换成小写或大写,然后再进行搜索。例如:

$str = "Hello, World! hello, PHP!";
$count = substr_count(strtolower($str), strtolower("hello"));
echo $count; // 输出2

在上面的例子中,strtolower()函数用于将字符串转换成小写,substr_count()函数返回2,因为在转换成小写之后,它匹配到了两个子字符串。

发表评论

快捷回复: 表情:
Addoil Applause Badlaugh Bomb Coffee Fabulous Facepalm Feces Frown Heyha Insidious KeepFighting NoProb PigHead Shocked Sinistersmile Slap Social Sweat Tolaugh Watermelon Witty Wow Yeah Yellowdog
提交
评论列表 (有 0 条评论, 54人围观)