Home > Mobile >  PHP Format Name using Array e.g. John Smith to John S
PHP Format Name using Array e.g. John Smith to John S

Time:01-21

$data['full_name'] stores the full name e.g. John Smith

At the moment I am using

$data['full_name'] = strtok($data['full_name'], " ");

This will convert the first name for me - E.g. John

I want to also include the second name - E.g. John S

CodePudding user response:

I would use a regex replacement here:

$input = "John Michael Smith";
$output = preg_replace("/(?<=\s)(\w)\w*/", "$1", $input);
echo $output;  // John M S

I used a regex pattern which will target all words in the name other than the first name and replace with just the first letter. The regex pattern used here says to match:

(?<=\s)  assert that a space precedes (excludes the first name)
(\w)     match and capture the first letter
\w*      then consume the rest of the name, without matching

We replace with $1, which is just the first letter of the name component.

CodePudding user response:

Use this code snippet

<?php
    $input = "John Smith";
    $name = explode(" ", $input);
    $formatted="";
    foreach ($name as $key => $value) {
   // code...
   if($key==0)
   $formatted.=$value;
  else{
  $formatted.=' '.substr($value, 0, 1);
  }
  }
  echo $formatted;
 ?>
  •  Tags:  
  • Related