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.
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: substr_count(string, substring, start, length) 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:
<?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>';
}
?>Output:
URL中存在子字符串cn<br/>URL中不存在 com<br/>Method 2: Using strpos()
Syntax: strpos(string, find, start) 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:
<?php
$url = 'http://www.php.cn';
$key = 'cn';
if (strpos($url, $key) == false) {
echo 'URL中不存在子字符串' . $key . ' <br>';
} else {
echo 'URL中存在子字符串 ' . $key . ' <br>';
}
$key1 = 'com';
if (strpos($url, $key1) == false) {
echo 'URL中不存在子字符串 ' . $key1;
} else {
echo 'URL中存在子字符串 ' . $key1;
}
?>Output:
URL中存在子字符串 cn
URL中不存在子字符串 comSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
