简体   繁体   中英

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

$data['full_name'] stores the full name eg John Smith

At the moment I am using

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

This will convert the first name for me - Eg John

I want to also include the second name - Eg John S

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.

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;
 ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM