0
0
PHPprogramming~5 mins

String search functions (strpos, strstr) in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the strpos function do in PHP?
It finds the position of the first occurrence of a substring in a string. If the substring is found, it returns the index (starting at 0). If not found, it returns false.
Click to reveal answer
beginner
What is the difference between strpos and strstr?
strpos returns the position (number) of the substring in the string. strstr returns the part of the string starting from the first occurrence of the substring to the end.
Click to reveal answer
beginner
What does strstr return if the substring is not found?
It returns false if the substring is not found in the string.
Click to reveal answer
intermediate
How does strpos handle the case when the substring is at the very start of the string?
It returns 0 because the substring starts at the first character (index 0). Remember, 0 is a valid position, not false.
Click to reveal answer
intermediate
How can you safely check if a substring exists using strpos?
Use the strict comparison operator !== false because strpos can return 0 (which is falsey). For example: if (strpos($text, 'word') !== false) { /* found */ }
Click to reveal answer
What does strpos('hello world', 'world') return?
A6
B0
Cfalse
D11
What will strstr('hello world', 'world') return?
A'world' plus the rest of the string starting from 'world'
B'hello world'
C'world' plus the rest of the string
D'world'
What does strpos('apple', 'a') return?
Afalse
B0
C1
D5
If strpos returns 0, what does that mean?
ASubstring found at the end
BSubstring not found
CError in function
DSubstring found at the start
Which is the correct way to check if 'cat' is in a string $text?
Aif (strpos($text, 'cat') == true) { ... }
Bif (strpos($text, 'cat')) { ... }
Cif (strpos($text, 'cat') !== false) { ... }
Dif (strpos($text, 'cat') == false) { ... }
Explain how strpos works and how to correctly check if a substring exists in a string.
Think about what happens if the substring is at the start.
You got /4 concepts.
    Describe the behavior of strstr and what it returns when the substring is found or not found.
    It returns a string, not a number.
    You got /3 concepts.