Using PHP strpos() to Find Character and Substring Positions
This article explains the PHP strpos() function, its syntax, parameters, and demonstrates how to locate characters or substrings within a string using various examples, including offset handling, with complete code snippets for practical reference.
In PHP, string handling often requires locating the position of a specific character or substring. The built‑in function strpos() is used for this purpose.
1. Basic usage of strpos()
The function returns the position of the first occurrence of the needle in the haystack, or false if not found. Its syntax is:
int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )$haystack is the target string, $needle is the character or substring to search for, and $offset (optional) specifies the starting index for the search.
2. Example: Find the character 'o'
Assume the following string:
$str = "Hello, world!";To find the position of the character 'o' :
$pos = strpos($str, 'o');
if ($pos === false) {
echo "未找到字符'o'";
} else {
echo "字符'o'在位置:" . $pos;
}The code searches for the first occurrence of 'o' and outputs its index (0‑based). The result is 4 .
3. Example: Find a substring
To locate the substring 'wor' within the same string:
$sub_str = 'wor';
$pos = strpos($str, $sub_str);
if ($pos === false) {
echo "未找到字符串'$sub_str'";
} else {
echo "字符串'$sub_str'在位置:" . $pos;
}This returns position 7 , the index of the first character of the substring.
4. Example: Search with an offset
When you need to start searching from a specific index, provide the $offset parameter:
$sub_str = 'o';
$pos = strpos($str, $sub_str, 5);
if ($pos === false) {
echo "未找到字符'$sub_str'";
} else {
echo "字符'$sub_str'在位置:" . $pos;
}With an offset of 5 , the function finds the next 'o' at index 8 .
Summary
The article introduces the PHP strpos() function, explains its parameters, and provides multiple code examples showing how to locate characters, substrings, and how to use the optional offset argument. Mastering this function simplifies many string‑processing tasks in backend development.
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.