6
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【PHP】名前をスペースで姓と名に分割する

Last updated at Posted at 2015-10-05

名前をスペースで姓と名に分割する処理。

手入力された値なので、姓と名の間のスペースが全角だったり半角だったり、スペース複数だったり。また、名前の前後にスペースが入っているなど。姓名がスペースで分かれてないものは姓の方に入れる。

list($last_name,$first_name) = split_name('鈴木  太郎 ');
var_dump($last_name);
var_dump($first_name);

function split_name($name){
    //1.全角スペースを半角スペースに変換
    $name = str_replace(' ', ' ', $name);
    //2.前後のスペース削除(trimの対象半角スペースのみなので半角スペースに変換後行う)
    $name = trim($name);
    //3.連続する半角スペースを半角スペースひとつに変換
    $name = preg_replace('/\s+/', ' ', $name);
    //姓と名で分割
    $name = explode(' ',$name);
    
    $last_name = $first_name = null;
    
    if(!empty($name[0])){
        $last_name = $name[0];
    }
    
    if(!empty($name[1])){
        $first_name = $name[1];
    }
    
    return [$last_name,$first_name];
}
6
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?