substr_count_PHP substr_count()函数与示例

substr_count

PHP substr_count()函数 (PHP substr_count() Function)

substr_count() function is a string function in PHP, it is used to find the total number of occurrences of a substring in the given string.

substr_count()函数是PHP中的字符串函数,用于查找给定字符串中子字符串出现的总数。

Syntax:

句法:

    substr_count(string, substring, [offset], [length]);

Here,

这里,

  • string is the main string in which we have to perform the search for the substring.

    string是我们必须在其中搜索子 字符串的主要字符串。

  • substring is the part of the string that we have search in the string.

    substring是我们在字符串中搜索的字符串的一部分 。

  • offset is an optional parameter, it defines the start index – from where you want to search the string. Its default value is 0.

    offset是一个可选参数,它定义了起始索引,即您要从中搜索字符串的位置。 默认值为0。

  • length is also an optional parameter, it defines length of the search i.e. search operation will start from offset and finishes with offset+length position.

    length也是一个可选参数,它定义了搜索的长度,即搜索操作将从offset开始,并以offset + length位置结束。

Examples:

例子:

    Input: 
    str = "Hello friends how are your friends?";
    substring = "friends";
    Output:
    2

    Input:
    str = "Hello friends how are your friends?";
    substring = "Hello";
    Output:
    1

    Input:
    str = "Hello friends how are your friends?";
    substring = "Hi";
    Output:
    0

PHP code:

PHP代码:

<?php
	$str = "Hello friends how are your friends?";
	$substring = "friends";
	$count = 0; //variable to store occurrences of the substrig
	
	//search will be performed in complete string
	$count = substr_count($str, $substring);
	echo ("$substring found $count times.\n");

	//search will be performed in complete string
	$substring = "Hi";
	$count = substr_count($str, $substring);
	echo ("$substring found $count times.\n");

	//search will be performed from 14th index
	$substring = "friends";
	$count = substr_count($str, $substring, 14);
	echo ("$substring found $count times.\n");	

	//search will be performed from 14th index to next 10 chars
	$substring = "friends";
	$count = substr_count($str, $substring, 14, 10);
	echo ("$substring found $count times.\n");		
?>

Output

输出量

friends found 2 times.
Hi found 0 times.
friends found 1 times.
friends found 0 times.


翻译自: https://www.includehelp.com/php/substr_count-function-with-example.aspx

substr_count

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值