Search code examples
phpregexstringcharactertrim

PHP Regex — Remove all characters but first from last word in string


I researched quite a long time before posting, but I couldn't come up with an answer.

I'm trying to remove all characters but the first from a string. The string is going to be a name. The name can have a first name and a last name, as well as a middle name. So my task is to explode the string into words and find the last one, remove the characters and add a dot to the first letter. Moreover, if present in the string, the middle name should not be in the result.

For example: Chuck Ray Norris should transform into Chuck N.

I tried a couple of regex and strpos but this task is too difficult for me and my skills.


Solution

  • A non-regex solution for "FirstName SecondName ThirdName... LastName" pattern:

    <?php
    $str = "Chuck Ray Norris";
    $spls = explode(" ", $str);
    echo $spls[0] . " " . $spls[count($spls)-1][0] . ".";
    

    Output:

    Chuck N.