Regex - Return First and Last Name

前端 未结 7 1119
一整个雨季
一整个雨季 2021-01-15 08:51

I\'m looking for the best reliable way to return the first and last name of a person given the full name, so far the best I could think of is the following

7条回答
  •  感情败类
    2021-01-15 09:20

    Instead of a regex you might find it easier to do something like:

    $parts = explode(" ", $name);
    $first = $parts[0];
    $last = ""
    if (count($parts) > 1) {
        $last = $parts[count($parts) - 1];
    }
    

    You might want to replace multiple consecutive bits of whitespace with a single space first, so you don't get empty bits, and get rid of trailing/leading whitespace:

    $name = ereg_replace("[ \t\r\n]+", " ", trim($name));
    

提交回复
热议问题