Understanding PHP's strstr() Function: Syntax, Usage, and Examples
This article explains PHP's strstr() function, covering its syntax, parameters, and practical examples such as finding the first occurrence, retrieving text before the needle, performing case‑sensitive and case‑insensitive searches, and handling multibyte characters with mb_strstr.
PHP is a widely used server‑side scripting language; one of its useful string functions is strstr(), which searches for the first occurrence of a needle in a haystack.
Syntax
strstr(string $haystack, mixed $needle, bool $before_needle = false): string|falseThe function takes three parameters: the haystack string, the needle string, and an optional boolean indicating whether to return the part before the needle.
Usage examples
1. Find first occurrence
$haystack = "Hello World!";<br>$needle = "World";<br>$result = strstr($haystack, $needle);<br>echo $result;This outputs World! because the substring from the needle to the end is returned.
2. Get text before the needle
$haystack = "Hello World!";<br>$needle = "World";<br>$result = strstr($haystack, $needle, true);<br>echo $result;The output is Hello, the part preceding the needle.
3. Case‑sensitive search
By default strstr() is case‑sensitive. Searching for "world" would fail.
Case‑insensitive search
$haystack = "Hello World!";<br>$needle = "world";<br>$result = stristr($haystack, $needle);<br>echo $result;This outputs World! using stristr().
4. Multibyte characters
For UTF‑8 strings, mb_strstr() should be used.
$haystack = "你好,世界!";<br>$needle = "世界";<br>$result = mb_strstr($haystack, $needle);<br>echo $result;The result is 世界!.
Summary
The strstr() function is versatile for locating substrings, extracting text before a needle, performing case‑insensitive searches with stristr(), and handling multibyte data via mb_strstr(), making it valuable for PHP developers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
