-6

Good Morning, I am trying to show the Initials of First and Last name but no luck. Tried to use substr () but no luck say Mr. abc xyz = should be shown as AX

thanks in advance,

substr ('Mr. abc xyz' ,  1 ); ?>"
Rahul W
  • 203
  • 3
  • 8
  • Write your whole code. – Mr. Kenneth Aug 18 '23 at 05:30
  • Does this answer your question? [How to get the first character of string in php](https://stackoverflow.com/questions/33890810/how-to-get-the-first-character-of-string-in-php) – Ram Chander Aug 18 '23 at 05:31
  • 3
    Don't fool yourself into thinking this is a simple problem. Consider "Dr James Earl van Houten III" as an example. You can throw out common prefixes and suffixes and grab the first letter of each word that remains. – Tim Roberts Aug 18 '23 at 05:31
  • 2
    Well, if some names are _prefixed_ with the person's title/profession(Mrs., Dr.,etc...), you would have to first know how to exclude them **before** tackling the issue at hand. Is the person's title/profession stored separately in the database? – steven7mwesigwa Aug 18 '23 at 05:48
  • `substr` will clearly not work on its own. Have you tried anything else like combining it with an `explode` and writing some extra code to process the result? – apokryfos Aug 18 '23 at 06:55
  • This is the long way but it works. **1** ```$str = "Mr. abc xyz";```. **2** ```$initials = explode(" ",$str);```. **3** ```echo strtoupper(substr($initials[1], 0, 1)).strtoupper(substr($initials[2], 0, 1));``` – Newbee Aug 18 '23 at 07:45

1 Answers1

-2
$str = 'Mr. abc xyz';
$arr = explode(' ', $str);
$arr = array_map(fn ($el) => rtrim($el, '.'), $arr);
echo $arr[1][0] . $arr[2][0];

but it is very bad example. If format will be change yu can get a very big problems)

Evg Vfv
  • 1
  • 1