Counts how many times a substring occurs in a string in PHP
The substr_count() is a built-in function in PHP and is used to count the number of times a substring occurs in a given string. The function also provides us with an option to search for the given substring in a given range of the index. It is case sensitive, i.e., the “abc” substring is not present in the string “Abcab”. If the (start+length) value specified for search exceeds the size of the passed string, it returns a warning message to the user.
Syntax:
substr_count($string, $substring, $start, $length);
Parameters: This function accepts four parameters as shown in the above syntax and described below.
- $string – The string passed in the parameter is the one in which the substring’s occurrence is counted. This parameter is mandatory to be supplied.
- $substring – The substring passed in the parameter is searched is the string and the occurrence count is returned. This parameter is mandatory to be supplied.
- $start – This parameter is optional. If this parameter is passed, then the search is done starting from the start position instead of searching the whole string for the occurrence of a substring.
- $length – This parameter is optional. The parameter is dependent on start. It limits the search operation from start to start+length position. If the value of start+length increases the length of the string, then a warning message is generated
Return Value: This function can return different values as shown below in different cases.
- The number of times the given substring appears in the string if optional parameters are not passed.
- The number of times the substring appears in the string from the start to the end position when start is passed in parameter.
- The number of times the substring appears in the string from the start to the start+length position when start and length both parameters are passed.
Example 1: When both optional parameters are not passed.<?php // PHP program to demonstrate the substr_count() function
$string = "Try not to become a man of success, but rather try to become a man of value.";
echo substr_count($string, 'man'); // Outputs: 2
?>
If you have any query or suggestions, feel free to ask me via the comment section below.
must watch some other topics :
0 Comments