PHP – How to cut out part of a string using iconv_substr()?

In PHP, the iconv_substr() function is used to cut out a portion of a string based on character position, with proper support for multibyte character encodings like UTF-8. This function is particularly useful when working with international text that may contain special characters.

Syntax

string iconv_substr(string $string, int $offset, ?int $length = null, ?string $encoding = null)

Parameters

  • $string − The original string to extract from

  • $offset − Starting position (0-based). If negative, counts from the end of the string

  • $length − Number of characters to extract. If omitted, extracts to the end of string

  • $encoding − Character encoding to use. Defaults to iconv.internal_encoding if not specified

Return Values

Returns the extracted substring on success, or false on failure. If the offset is beyond the string length, returns an empty string.

Example 1

Basic Usage

Extracting a substring from position 2, taking 7 characters ?

<?php
    // Extract substring from "HelloWorld!" starting at position 2
    $string = iconv_substr("HelloWorld!", 2, 7, "UTF-8");
    
    // Display the result
    var_dump($string);
?>
string(7) "lloWorl"

Example 2

Handling Spaces

Extracting substring that includes spaces ?

<?php
    // Extract substring from "Hello World!" with space included
    $string = iconv_substr("Hello World!", 2, 7, "UTF-8");
    
    // Display the result
    var_dump($string);
?>
string(7) "llo Wor"

Example 3

Negative Offset

Using negative offset to count from the end of the string ?

<?php
    // Extract 5 characters starting 6 positions from the end
    $string = iconv_substr("HelloWorld!", -6, 5, "UTF-8");
    
    // Display the result
    echo $string;
?>
World

Conclusion

The iconv_substr() function is essential for safely extracting substrings from multibyte character strings. Always specify the encoding parameter when working with international text to ensure proper character handling.

Updated on: 2026-03-15T09:56:38+05:30

311 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements