w3resource

PHP: substr_count() function

Description

The substr_count() function is used to count the number of times a substring occurs in a string. Note that substring is case sensitive.

Version:

(PHP 4 and above)

Syntax:

substr_count(string1, string2, nstart, nlength)

Parameters:

Name Description Required /
Optional
Type
string1 The string to search in. Required String
string2 The substring to search for. Required String
nstart The position where string to start searching. Optional Integer
nlength The length of the string to be searched for. Optional Integer

Return value:

Returns a number.

Value Type: Integer.

Pictorial Presentation

string_substr_count

Example:

<?php
$string1="Welcome to w3resource.com";
echo substr_count($string1,'co'); 
echo substr_count($string1,'co',4); 
echo substr_count($string1,'co',4,4); 
?>

Output:

2
1
0

View the example in the browser

See also

PHP Function Reference

Previous: substr_compare
Next: substr_replace



PHP: Tips of the Day

PHP: Using str_replace so that it only acts on the first match?

Can be done with preg_replace:

function str_replace_first($from, $to, $content)
{
    $from = '/'.preg_quote($from, '/').'/';

    return preg_replace($from, $to, $content, 1);
}

echo str_replace_first('abc', '123', 'abcdef abcdef abcdef'); 
// outputs '123def abcdef abcdef'

The magic is in the optional fourth parameter [Limit]. From the documentation:

[Limit] - The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).

Ref : https://bit.ly/35SCuP8