How does substr() function in PHP handle character encoding?

When using the substr() function in PHP to extract a portion of a string, it is important to consider character encoding. If the string contains multibyte characters, using substr() directly may result in broken or corrupted characters. To handle character encoding properly, you can use the mb_substr() function in PHP, which is specifically designed to work with multibyte character encodings.

// Using mb_substr() to handle character encoding when extracting a portion of a string
$originalString = "こんにちは、世界!"; // Japanese string with multibyte characters
$substring = mb_substr($originalString, 0, 5, 'UTF-8'); // Extract first 5 characters using UTF-8 encoding
echo $substring; // Output: こんにちは