Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP substr breaks emoji

Tags:

php

emoji

I need to get only 30 characters from the paragraph submitted by user. In case the 30th character is an emoji, the output shows question marks. How can I avoid breaking the emojis?

echo substr("Hello world Hello world Hell😄 ", 0, 30);

Output: Hello world Hello world Hell��

Also, when using json_encode to return the output, the output is blank.

$myvariable = array();
$myvariable['hello'] = substr("Hello world Hello world Hell😄 ", 0, 30);
echo json_encode($myvariable);
like image 234
Bhaskar Choudhary Avatar asked Jan 20 '26 15:01

Bhaskar Choudhary


1 Answers

I think the simplest solution would be to use mb_substr

Performs a multi-byte safe substr() operation based on number of characters.

php > $myvariable = array();
php > $myvariable['hello'] = mb_substr("Hello world Hello world Hell😄 ", 0, 30);
php > var_dump($myvariable);
array(1) {
  ["hello"]=>
  string(33) "Hello world Hello world Hell😄 "
}
php > echo json_encode($myvariable);
{"hello":"Hello world Hello world Hell\ud83d\ude04 "}
php > 
like image 81
Victor Smirnov Avatar answered Jan 22 '26 04:01

Victor Smirnov