Backend Development 4 min read

Using PHP substr_count() and strpos() Functions to Count and Locate Substrings

This article explains how to use PHP's substr_count() and strpos() functions to count occurrences of a substring and find its position within a string, providing syntax details, parameter descriptions, and complete code examples with expected output.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP substr_count() and strpos() Functions to Count and Locate Substrings

This article introduces two PHP functions, substr_count() and strpos() , which are used to count the number of occurrences of a substring and to locate the first position of a substring within a string, respectively.

Method 1: Using substr_count()

Syntax:

<code>substr_count(string, substring, start, length)</code>

string : the target string to be examined.

substring : the substring to search for.

start (optional): the position in the string to start searching.

length (optional): the length of the portion to search.

Return value: the number of times the substring appears in the string.

Example:

<code>&lt;?php
$url = 'http://www.php.cn';
$key = 'cn';
if (substr_count($url, $key) == false) {
    echo 'URL中不存在子字符串' . $key;
} else {
    echo 'URL中存在子字符串' . $key;
}

echo "<br>";
$key1 = 'com';
if (substr_count($url, $key1) == false) {
    echo 'URL中不存在子字符串 ' . $key1 . ' <br>';
} else {
    echo 'URL中存在 ' . $key1 . ' <br>';
}
?&gt;</code>

Output:

<code>URL中存在子字符串cn<br/>URL中不存在 com<br/></code>

Method 2: Using strpos()

Syntax:

<code>strpos(string, find, start)</code>

string : the string to be searched.

find : the substring to locate.

start (optional): the position to start searching.

Return value: the position of the first occurrence of the substring, or false if not found. Note: strpos() is case‑sensitive.

Example:

<code>&lt;?php
$url = 'http://www.php.cn';
$key = 'cn';
if (strpos($url, $key) == false) {
    echo 'URL中不存在子字符串' . $key . ' &lt;br&gt;';
} else {
    echo 'URL中存在子字符串 ' . $key . ' &lt;br&gt;';
}

$key1 = 'com';
if (strpos($url, $key1) == false) {
    echo 'URL中不存在子字符串 ' . $key1;
} else {
    echo 'URL中存在子字符串 ' . $key1;
}
?&gt;</code>

Output:

<code>URL中存在子字符串 cn 
URL中不存在子字符串 com</code>
backendPHPstring-functionssubstr_countstrpos
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.