How do you split a string using php?
For example, I have a table where a column is a full name of a person.
wholename
-------------
Smith, John B.
Pascal, Mary Anne A.
Dela Cruz, James Mark
Then I want to split it into three sections lastname
, firstname
, middleinital
lastname firstname middleinitial
---------- ---------- ----------
Smith John B.
Pascal Mary Anne A.
Dela Cruz James Mark
Then I want to output it into a site. So far, the code I have only stores the whole name in a session string.
Here have a answer to Split first and last name.
Now with variable $firstName
, you get middle name where have dot at first name.
if(strpos($nome, "."))
{
$middlename = substr($firstname, strrpos($firstname, " "));
$firstname = substr($firstname, 0, strrpos($firstname, " "));
}
Assuming this format, you can do it using this regular expression:
$regex = '/(?P<lastname>[a-zA-Z ]+)\,\s(?P<firstname>[a-zA-Z ]+)(\s(?P<middleinitial>\w\.)|$)/';
$wholenames = ['Smith, John B.', 'Pascal, Mary Anne A.', 'Dela Cruz, James Mark'];
foreach ($wholenames as $wholename) {
preg_match($regex, $wholename, $matches);
var_dump($matches['lastname']);
var_dump($matches['firstname']);
var_dump($matches['middleinitial']);
echo "-------------
";
}
Outputs:
string(5) "Smith"
string(4) "John"
string(2) "B."
-------------
string(6) "Pascal"
string(9) "Mary Anne"
string(2) "A."
-------------
string(9) "Dela Cruz"
string(10) "James Mark"
NULL
-------------