PHP – How to get the selected part of a string using mb_substr()?

PHPServer Side ProgrammingProgramming

In PHP, mb_substr() is used to return the selected part of a given string. The multibyte safe substr() works based on the number of characters. It counts the position from the starting of the string. It will return 0 for the first character position and 1 for the second position character, and so on.

Syntax

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

Parameters

This PHP function accepts four parameters: $string, $start, $length and $encoding.

  • $string− This parameter is used to extract the substring from the given string.

$string = mb_substr("Welcome to the online tutorials!", 5, 10, "UTF-8");
  • $start− This parameter returns 0 for the first character from starting if the start is non-negative. For example, if the given string is “abcefg” then the character at the first position is 0 means “a” and so on. If the start string is negative, then it will return the character from the end of the string.

  • $length− The length parameter is the maximum number of characters to use from the string.

// Length is used from character (5 to 10) (5, 10, "UTF-8");
  • $encoding− It is used for character encoding. If it is omitted or null, the internal character encoding value will be used.

Return Values

The multibyte substring function will return the selected portion from the given string by using the start and length parameters.

Example

 Live Demo

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

Output

ME TO THE
raja
Published on 23-Aug-2021 08:22:01
Advertisements