Using PHP strpos() to Find Character and Substring Positions
This article explains PHP's strpos() function, covering its syntax and demonstrating how to locate characters, substrings, and use an offset through clear code examples, enabling developers to efficiently perform string position searches.
In PHP, string handling often requires locating the position of a specific character or substring, which can be done using the built‑in strpos() function.
1. Basic usage of strpos()
The function returns the position of the first occurrence of a needle in a haystack, or false if not found. Its signature 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 where to start the search.
2. Example: finding a character
Given $str = "Hello, world!" , the following code finds the position of the character 'o' :
$pos = strpos($str, 'o');
if ($pos === false) {
echo "Character 'o' not found";
} else {
echo "Character 'o' is at position: " . $pos;
}The script outputs: Character 'o' is at position: 4 .
3. Example: finding a substring
To locate the substring 'wor' :
$str = "Hello, world!";
$sub_str = 'wor';
$pos = strpos($str, $sub_str);
if ($pos === false) {
echo "Substring 'wor' not found";
} else {
echo "Substring 'wor' is at position: " . $pos;
}The result is: Substring 'wor' is at position: 7 .
4. Example: using an offset
Searching for 'o' starting from index 5:
$str = "Hello, world!";
$sub_str = 'o';
$pos = strpos($str, $sub_str, 5);
if ($pos === false) {
echo "Character 'o' not found";
} else {
echo "Character 'o' is at position: " . $pos;
}The output is: Character 'o' is at position: 8 .
Conclusion
The article demonstrates the basic syntax of strpos() and shows how to use it to locate characters, substrings, and to start searches from a specific offset, helping developers handle string‑related tasks more efficiently.
PHP8 video tutorial – Scan the QR code to get free learning materials.
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.