PHP strpos() function
The strpos()
function in PHP is used to find the position of the first occurrence of a substring within a string. If the substring is found, strpos()
returns the position (index) of the first occurrence of the substring. If the substring is not found, it returns false
.
Syntax:
- $haystack: The string to search in.
- $needle: The substring to search for.
- $offset (optional): The position in the string where the search should start. Default is 0 (the beginning of the string).
Return Value:
- If the substring is found,
strpos()
returns the numeric position (starting from 0). - If the substring is not found, it returns
false
.
Important Note:
- Since
strpos()
can return0
(if the substring is found at the start of the string), you should use the===
operator to check the return value to avoid confusion between0
(found at the start) andfalse
(not found).
Example 1: Basic Usage
Output:
Explanation: The substring "World"
starts at index 6
in the string "Hello World"
.
Example 2: Substring Not Found
Output:
Explanation: The substring "PHP"
does not exist in the string "Hello World"
, so strpos()
returns false
.
Example 3: Starting the Search at a Specific Position (Offset)
Output:
Explanation: By specifying an offset of 10
, strpos()
starts the search after the first occurrence of "World"
. The next occurrence of "World"
starts at position 24
.
Example 4: Using Strict Comparison (===
) to Avoid False Positives
Output:
Explanation: Since "Hello"
is at the very beginning of "Hello World"
, the strpos()
function returns 0
. To avoid confusion with false
, we use the strict comparison (===
) to correctly detect the position as 0
.
Example 5: Case Sensitivity
The strpos()
function is case-sensitive, meaning it treats uppercase and lowercase letters as different characters.
Output:
Explanation: The lowercase "world"
is not found because strpos()
is case-sensitive. To make a case-insensitive search, you can use stripos()
instead.
Key Points:
strpos()
returns the position of the first occurrence of a substring, orfalse
if not found.- Use the strict comparison operator (
===
) to distinguish betweenfalse
(not found) and0
(found at the start of the string). - The search can be started from a specific position using the optional offset parameter.
- It is case-sensitive by default.
This function is commonly used for tasks like searching, filtering, and string manipulation in PHP.