0
0
PHPprogramming~15 mins

String search functions (strpos, strstr) in PHP - Deep Dive

Choose your learning style9 modes available
Overview - String search functions (strpos, strstr)
What is it?
String search functions in PHP help you find if a smaller piece of text exists inside a bigger text. Two common functions are strpos and strstr. strpos tells you the position where the smaller text starts, while strstr returns the part of the bigger text starting from the smaller text. These functions make it easy to check and extract parts of strings.
Why it matters
Without string search functions, you would have to manually check each character to find text inside strings, which is slow and error-prone. These functions save time and make your code simpler when working with text, like searching for words in a sentence or extracting data from messages. They are essential for tasks like form validation, parsing, and text processing.
Where it fits
Before learning string search functions, you should understand basic strings and variables in PHP. After mastering these functions, you can learn about regular expressions for more powerful text searching and manipulation.
Mental Model
Core Idea
String search functions quickly locate or extract parts of text inside a bigger string based on a smaller search string.
Think of it like...
It's like looking for a word in a book: strpos tells you the page number where the word first appears, while strstr gives you the page starting from that word to the end.
Big string:  ┌─────────────────────────────┐
Search text:           ┌─────┐
strpos result:         ↑ (position index)
strstr result:        ┌─────────────────────┐
                      │ substring from here │
                      └─────────────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding basic strings in PHP
🤔
Concept: Learn what strings are and how PHP stores text.
A string is a sequence of characters like letters or numbers. In PHP, strings are written inside quotes, for example: $text = "Hello World"; This stores the text so you can use it later.
Result
You can create and print text stored in variables.
Knowing what strings are is the first step to searching inside them.
2
FoundationUsing strpos to find text position
🤔
Concept: strpos finds the position of a smaller string inside a bigger string.
$text = "Hello World"; $pos = strpos($text, "World"); echo $pos; // Outputs 6 strpos returns the index where "World" starts in $text. Counting starts at 0.
Result
The output is 6, meaning "World" starts at the 7th character.
strpos helps you know exactly where a piece of text begins inside another.
3
IntermediateHandling strpos when text not found
🤔Before reading on: do you think strpos returns false or -1 if text is missing? Commit to your answer.
Concept: Learn how strpos behaves when the search text is not found.
$text = "Hello World"; $pos = strpos($text, "PHP"); var_dump($pos); // Outputs bool(false) strpos returns false if the text is not found, not -1.
Result
The output is bool(false), indicating no match.
Understanding strpos returns false prevents bugs when checking search results.
4
IntermediateUsing strstr to extract substring
🤔Before reading on: do you think strstr returns the part before or after the search text? Commit to your answer.
Concept: strstr returns the part of the string starting from the search text to the end.
$text = "Hello World"; $part = strstr($text, "World"); echo $part; // Outputs "World" strstr returns the substring starting at "World".
Result
The output is "World".
strstr lets you extract text from a certain point, useful for parsing.
5
IntermediateCase sensitivity in strpos and strstr
🤔Before reading on: do you think strpos and strstr ignore uppercase/lowercase differences? Commit to your answer.
Concept: By default, strpos and strstr are case sensitive, meaning uppercase and lowercase letters must match exactly.
$text = "Hello World"; $pos = strpos($text, "world"); var_dump($pos); // Outputs bool(false) Use stripos or stristr for case-insensitive search.
Result
The output is bool(false) because "world" != "World".
Knowing case sensitivity helps avoid unexpected search failures.
6
AdvancedUsing offset parameter in strpos
🤔Before reading on: do you think offset moves the search start forward or backward? Commit to your answer.
Concept: strpos can start searching from a specific position using the offset parameter.
$text = "Hello Hello World"; $pos = strpos($text, "Hello", 1); echo $pos; // Outputs 6 This skips the first character and finds the second "Hello".
Result
The output is 6, the position of the second "Hello".
Using offset allows finding multiple occurrences by skipping earlier matches.
7
ExpertCommon pitfalls with strpos false vs zero
🤔Before reading on: do you think strpos returning 0 means false or a valid position? Commit to your answer.
Concept: strpos returns 0 if the search text is at the start, which is different from false meaning not found.
$text = "Hello World"; if (strpos($text, "Hello") == false) { echo "Not found"; } else { echo "Found"; } // Outputs "Not found" incorrectly Use strict comparison === to fix: if (strpos($text, "Hello") === false) { echo "Not found"; } else { echo "Found"; }
Result
The first code wrongly says "Not found"; the fixed code correctly says "Found".
Understanding strict comparison prevents bugs when the match is at position zero.
Under the Hood
PHP string search functions work by scanning the string from left to right, comparing each character to the search string. strpos returns the index of the first character where the match starts, or false if none found. strstr returns a pointer to the substring starting at the match. Internally, PHP uses efficient algorithms optimized in C to perform these operations quickly.
Why designed this way?
These functions were designed to be simple and fast for common string search needs. Returning false instead of -1 follows PHP's convention for failure signals. The strict comparison requirement arises because 0 is a valid position, so false must be distinguishable. The offset parameter allows flexible searching without extra code.
Input string:  H e l l o   W o r l d
Index:         0 1 2 3 4 5 6 7 8 9 10

strpos search:           ┌─────┐
                         │World│
                         └─────┘

Result: position 6 or false

strstr returns substring starting at index 6:
World
Myth Busters - 4 Common Misconceptions
Quick: Does strpos return -1 when text is not found? Commit to yes or no.
Common Belief:strpos returns -1 if the search text is missing.
Tap to reveal reality
Reality:strpos returns false, not -1, when the text is not found.
Why it matters:Checking for -1 instead of false causes bugs where missing text is treated as found.
Quick: Is strpos case-insensitive by default? Commit to yes or no.
Common Belief:strpos ignores uppercase or lowercase differences when searching.
Tap to reveal reality
Reality:strpos is case-sensitive; it treats uppercase and lowercase letters as different.
Why it matters:Assuming case-insensitivity leads to missed matches and incorrect program behavior.
Quick: Does strpos returning 0 mean the text was not found? Commit to yes or no.
Common Belief:If strpos returns 0, it means the text was not found.
Tap to reveal reality
Reality:A return value of 0 means the text was found at the very start of the string.
Why it matters:Misinterpreting 0 as false causes false negatives and bugs in condition checks.
Quick: Does strstr return the part before the search text? Commit to yes or no.
Common Belief:strstr returns the part of the string before the search text.
Tap to reveal reality
Reality:strstr returns the part of the string starting from the search text to the end.
Why it matters:Wrong assumptions about strstr output cause incorrect string processing.
Expert Zone
1
strpos and strstr operate on byte-level, so multibyte characters (like UTF-8 emojis) can cause unexpected positions unless using mb_strpos or mb_strstr.
2
Using strict comparison (===) with strpos is critical to distinguish between position 0 and false, preventing subtle bugs.
3
The offset parameter in strpos can be negative in PHP 7.1+, allowing search from the end, a less known but powerful feature.
When NOT to use
Avoid strpos and strstr when working with multibyte or Unicode strings; use mb_strpos and mb_strstr instead. For complex pattern matching, use regular expressions with preg_match. When performance is critical on large texts, specialized search algorithms or libraries may be better.
Production Patterns
In real-world PHP apps, strpos is often used for quick checks like validating input or routing URLs. strstr helps extract query parameters or substrings after known markers. Developers combine these with strict checks and fallback logic to handle missing or malformed data safely.
Connections
Regular expressions
Builds-on
Knowing simple string search functions prepares you to understand regular expressions, which allow more flexible and powerful text matching.
Memory searching algorithms (e.g., Boyer-Moore)
Underlying principle
String search functions rely on efficient algorithms like Boyer-Moore to quickly find substrings, connecting programming to algorithm design.
Textual data retrieval in databases
Similar pattern
Searching strings in PHP is conceptually similar to how databases search text fields, linking programming to data management.
Common Pitfalls
#1Confusing strpos return 0 with false
Wrong approach:if (strpos($text, "Hello") == false) { echo "Not found"; }
Correct approach:if (strpos($text, "Hello") === false) { echo "Not found"; }
Root cause:Using loose comparison (==) treats 0 as false, hiding valid matches at string start.
#2Assuming case-insensitive search by default
Wrong approach:$pos = strpos($text, "world"); if ($pos !== false) { echo "Found"; }
Correct approach:$pos = stripos($text, "world"); if ($pos !== false) { echo "Found"; }
Root cause:Not knowing strpos is case-sensitive leads to missed matches.
#3Using strstr expecting substring before search text
Wrong approach:$part = strstr($text, "World"); echo $part; // expecting "Hello "
Correct approach:$part = strstr($text, "World"); echo $part; // outputs "World"
Root cause:Misunderstanding strstr returns substring from search text, not before.
Key Takeaways
strpos and strstr are essential PHP functions to find and extract parts of strings based on smaller search strings.
strpos returns the position index or false if not found; strict comparison is needed to handle position zero correctly.
strstr returns the substring starting from the search text to the end, not the part before it.
Both functions are case-sensitive by default; use stripos and stristr for case-insensitive searches.
Understanding these functions deeply prevents common bugs and prepares you for advanced text processing.