Open In App

PHP mb_strstr() Function

Last Updated : 28 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads