-1

I'm using the following code to display only the last name first character on my Wordpress site:

$name = $comment->comment_author;
$separate = mb_split(" ", $name);
$last = array_pop($separate);
echo implode(' ', $separate)." ".$last[0].".";

It works great with English names, but $last[0] will return a question mark when used with a foreign language (e.g Arabic, Hebrew, Greek etc). For example:

Name: השם שלי

Will return:

השם ?.

I've been trying to fix this for an hour now, but nothing so far.

Any idea?

John Smith
  • 67
  • 1
  • 1
  • 14
  • Index-based access on strings accesses a single _byte_, not necessarily a _character_ (which could consist of _multiple_ bytes.) https://stackoverflow.com/questions/1396434/what-is-the-best-way-to-split-a-string-into-an-array-of-unicode-characters-in-ph has ways to split a string value into _characters_. – CBroe Apr 21 '20 at 11:23
  • From the dupe *This is important if you're using multibyte encodings (such as UTF-8). If you want to support that, use `mb_substr()`* – Nigel Ren Apr 21 '20 at 11:25
  • https://www.w3.org/International/questions/qa-personal-names. The only robust solution is to actually ask people how they wish to be called / their name to be displayed. Don't assume anything about that value, just treat it as a single string. In particular, there is no reason to assume that a single character of any part of a name makes any sense by itself. – Peter Apr 21 '20 at 12:10

1 Answers1

0

You can try to set the encoding (https://www.php.net/manual/ro/function.mb-internal-encoding.php) before using the mb_split function.

Radu
  • 1,159
  • 3
  • 22
  • 40