Thursday, October 9, 2025
HomeLanguagesPHP mb_strstr() Function

PHP mb_strstr() Function

The mb_strstr() function is an inbuilt function in PHP that finds the first occurrence of a given string in the main string, i.e. it will search for the occurrence of the first needle in haystack, & id found then the portion of the haystack will be returned, otherwise return false.

Syntax:

mb_strstr(
    string $haystack,
    string $needle,
    bool $before_needle = false,
    ?string $encoding = null
): string|false

Parameters: This function accepts four parameters that are described below:

  • $haystack: This is the string where we search our substring. It is required must be a valid string
  • $needle: This is the substring that you want to find in the $haystack string. It also must be a valid string.
  • $before_needle:  This is the optional parameter that determines whether to return haystack after or before $needle occurs. If this parameter is “true” it will return beginning to the first occurrence of the $needle string (excluding needle). If this parameter is set to “false”, It will return from the beginning of the $needle to the $needle end.
  • $encoding:  This is the optional parameter that specifies the character encoding in the $haystack and $needle parameters. if the encoding is not provided it will use character encoding used.

Return Values: This function returns the portion of $haystack, if the needle is found in a $haystack otherwise it will return “false”.

Example 1: The following program demonstrates mb_strstr() function.

PHP




<?php
  
$string = "Hello, world!";
$sub = "world";
  
$pos = mb_strstr($string, $sub);
  
echo $pos;
?>


Output:

world!     

Example 2: The following program demonstrates mb_strstr() function

PHP




<?php
  
$string = "Geeks for Geeks";
$sub = "for";
  
$pos = mb_strstr($string, $sub, true);
  
echo $pos;
  
?>


Output:

Geeks 

Reference: https://www.php.net/manual/en/function.mb-strstr.php

RELATED ARTICLES

Most Popular

Dominic
32344 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6714 POSTS0 COMMENTS
Nicole Veronica
11877 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11940 POSTS0 COMMENTS
Shaida Kate Naidoo
6834 POSTS0 COMMENTS
Ted Musemwa
7094 POSTS0 COMMENTS
Thapelo Manthata
6789 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS