Current Location: Home> Latest Articles> iconv_substr: How to Prevent "Character Truncation" Errors When Substringing?

iconv_substr: How to Prevent "Character Truncation" Errors When Substringing?

M66 2025-07-25

3. Causes of the "Character Truncation" Error

  • : The default encoding might not match your string's actual encoding, leading to incorrect byte count during substring operations.

  • Substring length exceeds actual character count: An error may occur if the substring position goes beyond the string length.

  • Inconsistent or corrupted encoding within the string itself.


4. How to Prevent the "Character Truncation" Error?

  1. Explicitly specify the encoding

$encoding = 'UTF-8';
$result = iconv_substr($str, $offset, $length, $encoding);
</span>
  1. Ensure that substring length and offset are based on characters, not bytes

iconv_substr’s $offset and $length are counted in characters, not bytes, but the string must be in the specified encoding.

  1. Check string length in advance

Use iconv_strlen to determine the string length and avoid out-of-bound errors:

$length = iconv_strlen($str, $encoding);
if ($offset > $length) {
    // Handle offset out of bounds
}
</span>
  1. Error handling

iconv_substr may return false on failure, so proper checks are necessary:

$result = iconv_substr($str, $offset, $length, $encoding);
if ($result === </span>false) {
    // Handle substring failure to prevent program errors
}
</span>
  1. Use mbstring functions as an alternative

mb_substr is also a multibyte-safe substring function, often used as a replacement for iconv_substr:

$result = mb_substr($str, $offset, $length, $encoding);
</span>

5. Sample Code

<?php
$str = "This is a test string demonstrating how to use iconv_substr.";
$encoding = 'UTF-8';
$offset = 3;
$length = 5;
<p data-is-last-node="" data-is-only-node=""></span>$totalLength = iconv_strlen($str, </span>$encoding);<br>
if ($offset > </span>$totalLength) {<br>
</span>echo "Substring start position exceeds string length.";<br>
} </span>else {<br>
</span>$substr = </span>iconv_substr(</span>$str, </span>$offset, </span>$length, </span>$encoding);<br>
</span>if ($substr === false) {<br>
echo "Substring operation failed, possibly due to encoding issues.";<br>
} else {<br>
echo "Substring result: " . $substr;<br>
}<br>
}<br>
?><br>
</span></span>