Current Location: Home> Function Categories> mb_strpos

mb_strpos

Find where the string first appears in another string
Name:mb_strpos
Category:Multi-byte string
Programming Language:php
One-line Description:Find the first occurrence location of another substring in one string

Function name: mb_strpos()

Applicable version: PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8

Function Description: The mb_strpos() function is used to find the first occurrence location of another substring in one string. Similar to the strpos() function, but the mb_strpos() function can handle multibyte characters.

Syntax: mb_strpos(string $haystack, string $needle, int $offset = 0, string $encoding = null): int|false

parameter:

  • $haystack: Required, string in which to look for substrings.
  • $needle: Required, substring to be found.
  • $offset: optional, specify the location to start the search, default is 0.
  • $encoding: optional, specify character encoding, default to internal character encoding.

Return value:

  • If a substring is found, it returns its first occurrence position (in integer form).
  • If no substring is found, false is returned.

Example:

 // 示例1:在一个字符串中查找子字符串的位置$str = "Hello, World!"; $pos = mb_strpos($str, "World"); echo $pos; // 输出:7 // 示例2:在一个字符串中查找子字符串的位置,指定开始搜索的位置$str = "Hello, World!"; $pos = mb_strpos($str, "o", 5); echo $pos; // 输出:8 // 示例3:在一个多字节字符串中查找子字符串的位置,指定字符编码$str = "你好,世界!"; $pos = mb_strpos($str, "世界", 0, "UTF-8"); echo $pos; // 输出:6 // 示例4:未找到子字符串的情况下返回false $str = "Hello, World!"; $pos = mb_strpos($str, "abc"); var_dump($pos); // 输出:bool(false)

Notes:

  • The mb_strpos() function is very useful for multibyte characters, especially when using UTF-8 encoding.
  • If no character encoding is specified, internal character encoding is used by default.
Similar Functions
Popular Articles