首页 > 文章列表 > PHP - 如何使用mb_substr()函数获取字符串的选定部分?

PHP - 如何使用mb_substr()函数获取字符串的选定部分?

482 2023-08-20

在PHP中,mb_substr()用于返回给定字符串的选定部分。多字节安全的substr()是根据字符数工作的。它从字符串的起始位置计算位置。它将返回第一个字符位置为0,第二个字符位置为1,依此类推。

Syntax

string mb_substr(str $string, int $start, int $length, str $encoding)

参数

这个PHP函数接受四个参数:$string$start$length$encoding

  • $string− 这个参数用于从给定的字符串中提取子字符串。

$string = mb_substr("Welcome to the online tutorials!", 5, 10, "UTF-8");
  • $start− 此参数返回从起始位置开始的第一个字符的索引,如果起始位置是非负数,则返回0。例如,如果给定的字符串是“abcefg”,那么第一个位置的字符索引为0,表示“a”,依此类推。如果起始字符串是负数,则从字符串末尾返回字符。

  • $length− length参数是从字符串中使用的最大字符数。

// Length is used from character (5 to 10) (5, 10, "UTF-8");
  • $encoding− 它用于字符编码。如果省略或为空,将使用内部字符编码值。

返回值

多字节子字符串函数将使用startlength参数从给定的字符串中返回所选部分。

示例

 在线演示

<?php
   // the mb_substr function will return
   // the selected part of string
   $string = mb_substr("Welcome to the online tutorials!", 5, 10, "UTF-8");

   // Convert selected string in upper case
   $string = mb_convert_case($string, MB_CASE_UPPER, "UTF-8");

   // Output will be me to the
   echo "$string";
?>

输出

ME TO THE