I try to remove the last character from a string with Japanese text and emojis using this code:

<?php

$text = "私の名前はダバーです👩‍🚀";
$new_text = substr($text, 0, strlen($text) - 1);
echo $new_text;

The output breaks the characters and shows garbage. How do I fix this?

Use mb_substr() instead of substr(). It handles multibyte characters and emojis correctly.

Here is the correct code:

$text = "私の名前はダバーです👩‍🚀";
$length = mb_strlen($text, 'UTF-8');
$new_text = mb_substr($text, 0, $length - 1, 'UTF-8');
echo $new_text;

https://flatcoding.com/tutorials/php/php-remove-last-character-from-string/
This code removes the last character without breaking the text

Use mb_substr() instead of substr(). It handles multibyte characters and emojis correctly.

Here is the correct code:

$text = "私の名前はダバーです👩‍🚀";
$length = mb_strlen($text, 'UTF-8');
$new_text = mb_substr($text, 0, $length - 1, 'UTF-8');
echo $new_text;

https://flatcoding.com/tutorials/php/php-remove-last-character-from-string/
This code removes the last character without breaking the text

Thank you so much, it worked

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.