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


在 PHP 中,**mb_substr()** 用于返回给定字符串的选定部分。多字节安全的 **substr()** 基于字符数量工作。它从字符串的开头计算位置。它将返回第一个字符位置的 0 和第二个字符位置的 1,依此类推。

语法

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−** 如果 start 为非负数,则此参数从开头返回第一个字符的 0。例如,如果给定字符串为 **“abcefg”**,则第一个位置的字符为 0,即 **“a”**,依此类推。如果 start 字符串为负数,则它将返回字符串末尾的字符。

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

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

返回值

多字节子字符串函数将使用 **start** 和 **length** 参数从给定字符串中返回选定的部分。

示例

 在线演示

<?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

更新于: 2021-08-23

2K+ 阅读量

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.