PHP mb_strpos() Function

The mb_strpos() function is an inbuilt function in PHP that finds the position of string occurrence in the string.

Syntax:

mb_strpos(  $haystack, $needle, $offset, $encoding ): int|false

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

  • $haystack: This parameter is the main string parameter where we check the string.
  • $needle: This parameter is searching string parameter in the main string.
  • $offset: This parameter is an optional parameter. It is used for defining where you are to start searching string in the $haystack parameter.
  • $encoding:  This parameter is also optional. It is used for defining an encoding by using the mb_internal_encoding() function.

Return Values: This function returns return the integer of the first occurrence of $needle in the $haystack parameter. If $needle does not find in the $haystack parameter, it will return “false”.

Example 1:  The following code demonstrates the mb_strpos() function.

PHP




<?php
$string = "This is a test string";
$substring = "test";
  
$position = mb_strpos($string, $substring);
  
// Output the position
echo $position;
?>


Output:

10

Example 2: The following code demonstrates the mb_strpos() function.

PHP




<?php
$string = "w3wiki";
$substring = "test";
  
if (mb_strpos($string, $substring)) {
    echo "Substring is found";
} else {
    echo "Substring is not found";
}
?>


Output:

Substring is not found 

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