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

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.

  • $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.

  • $encoding − It is used for character encoding. If it is omitted or null, the internal character encoding value will be used.

Return Value

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

Example

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

Using Negative Start Position

When using a negative start position, mb_substr() counts from the end of the string ?

<?php
    $text = "Hello World!";
    
    // Extract last 6 characters
    $result = mb_substr($text, -6, 6, "UTF-8");
    echo "Last 6 chars: " . $result . "<br>";
    
    // Extract 5 characters starting from 6th position from end
    $result2 = mb_substr($text, -6, 5, "UTF-8");
    echo "5 chars from position -6: " . $result2;
?>
Last 6 chars: World!
5 chars from position -6: World

Conclusion

The mb_substr() function is essential for safely extracting substrings from multibyte character strings. Use negative positions to count from the end and always specify encoding for consistent results.

Updated on: 2026-03-15T09:57:46+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements