It's relatively a common requirement to split a string from a potential splitter:
$name = 'John'; // or can be 'John Smith'
I use
list($firstName, $lastName) = explode(' ', $name) + [1 => null];
or
#list($firstName, $lastName) = explode(' ', $name);
I wonder if you guys use a more concise or more legible method for this?
Oh, I found it!
list($firstName, $lastName) = explode(' ', $name.' ');
The simple trick is appending the glue string to the end of the main string. Tadda!
This make accessing to the second part of the string really easy:
$domain = explode('#', $filter->email . '#')[1]; // for an invalid input the domain will be ''.
Use array_pop to get last_name and all in first_name. Your code not works for name which have three words. Example below also works for three words in name like Niklesh Kumar Raut
Uncomment one $name and comment two to check
//$name = "Niklesh";
//$name = "Niklesh Raut";
$name = "Niklesh Kumar Raut";
$name_arr = explode(" ",$name);
$last_name = array_pop($name_arr);
$first_name = implode(" ",$name_arr);
echo "First Name : $first_name\n";//Niklesh Kumar
echo "Last Name : $last_name";//Raut
Live demo : https://eval.in/871971
you can use regex to check if the string contains space in between, and then explode using the space to get the first and last string.
$name = 'john smith';
$first_name = $name;
$last_name = '';
if(preg_match('/\s/',$name)) {
list($first_name, $last_name) = explode(' ', $name);
}
echo "Hello ".$first_name." ".$last_name;
Related
I have an array which contains the full name. I know how to display the last name which basically resides in the 1st index. How can I display the rest of the values after the last name?
$fullname = array('fullname' => 'POTTER Harry James');
$res = implode("", $fullname);
$name = preg_split("/[\s,]+/", $res);
$lname = $name[0];
What i did in the first name:
$fname = $name[1]. " ".$name[2];
It works fine, but is there a cleaner way to do that? I mean, what if the user has more than 2 first names?
Thanks.
I suggest to use explode() function:
<?php
$fullname = array('fullname' => 'POTTER Harry James');
$parts = explode(' ', $fullname['fullname']);
var_dump($parts);
?>
Shows:
array(3) {
[0]=>
string(6) "POTTER"
[1]=>
string(5) "Harry"
[2]=>
string(5) "James"
}
You might use any part of $parts in a way, that you need.
<?php
$a = array_shift($parts);
$b = implode(' ', $parts);
echo "{$b} ({$a})"; // Harry James (POTTER)
?>
UPDv1:
In your current code, you might do just the same thing:
<?php
$lname = array_shift($name);
$fname = implode(' ', $name);
?>
I think you should take out the last name off the array first, then use a loop to concatenate the remaining names as fistname.
$fullname = array('fullname' => 'POTTER Harry James');
$res = implode("", $fullname);
$name = preg_split("/[\s,]+/", $res);
$lname = array_shift($name);
$fname = "";
foreach($name as $fnames)
$fname.= " ".$fnames;
$fullname = array('fullname' => 'POTTER Harry James');
$firstNames = strstr($fullname['fullname'], ' '); // $firstNames='Harry James'
This gets the string after the first space character.
This is a bit of an impossible task. If left to their own devices, users are going to put all sorts of stuff into a single field.
If you care about separating the first and last names of your users, you should ask for them separately, as there is no regex that can possibly determine the correct way to break up their name.
You could do
<?php
$fullname = array('fullname' => 'POTTER Harry James');
list($lname,$fname) = explode(" ", $fullname["fullname"],2);
echo $fname."<br>".$lname;
?>
This will work if the name contains 2 words or more. In case there are more than 2 words then anything except the first word will be considered as first name and first word will be considered as the last name.
I am taking a list of names and putting the last name first. When I use explode to create the $name array, the first name has the first name in array position 0 and the last name at position 1, but the other names all start with first name at position 1 and last name at position 2.
I copied this code from another script that does similar things, but in that code all of the first names, including the first instance, start at number 1 (at least its consistent).
I'm guessing I'm missing something fundamental. I appreciate your assistance.
The code follows.
$_511a = 'Maria Smith, Lance Farquardt, Daniel Berquist, John Barton, Milo Silver';
echo '511a: ' . $_511a . '<br />';
$castsplit = explode(',' , $_511a);
foreach($castsplit as $cast) {
$name = explode(' ',$cast);
$lastname = end($name);
if(count($name) >= 4){
$middlename = $name[2];
} else {
$middlename = null;
}
$firstname = $name[1];
if($middlename){
$castmembers[] = $lastname . ', ' . $firstname . ' ' . $middlename;
} else {
$castmembers[] = $lastname . ', ' . $firstname;
}
}
echo "Corrected names: <br />";
foreach($castmembers as $castmember) {
echo $castmember . '<br />';
}
After the first name in the list all the names are preceded by a space. explode() counts that space, putting a blank string in the 0 index in the resulting array.
Change:
$name = explode(' ',$cast);
To:
$name = explode(' ',ltrim($cast));
The problem is a space after a comma between names. Either use exclusively "," or ", " as a separator, or use regular expression to split the string.
$castsplit = preg_split('/,\s*/', $_511a);
The above will accept all separators alike to this: <comma><zero or more spaces>.
You have spaces in between the string '$_511a' so explode function must have a space also. so the index of $name will also be changed because now we have the first element on 0 index.
change code
$castsplit = explode(',' , $_511a);
to
$castsplit = explode(', ' , $_511a);
and
$firstname = $name[1];
to
$firstname = $name[0];
try maybe:
$castsplit = explode(", ", $_511a);
//your variable name cast is ambiguous. I changed it
foreach($castsplit as $member) {
$nameArr = explode(' ', $member);
$first = $nameArr[0];
$last = end($nameArr);
str_replace($first, $last, $member, 1);
str_replace($last, $first, $member, 1);
echo $member;
}
notice the space after the comma in the first explode
I'm having some trouble parsing a first name and last name from a string into 2 different variables.
The string is always in this format: "Smith, John" or "Doe, Jane"
Is there a function out that can split the first and last name to 2 different variables to something like...
$firstname = "John"
$lastname = "Smith"
Use list with explode like this:
list($firstname, $lastname) = explode(',', $yourString);
You may need to use trim to remove any whitespace from those vars.
explode() splits a string based upon another string and returns an array.
You could do:
$name = "Smith, John";
$name_array = array();
$name_array = explode(",", $name);
I would go with regexp for this so that there could be slight variations in the input (i.e. "Smith, John", "Smith ,John", "Smith , John" or "Smith,John")
You could do something like this for regexp "\w([a-z]+)\w" and then last name would be your first match and first name would be your second match.
$name = "Smith, John";
$expl = explode(', ', $name);
$firstname = $expl[1];
$lastname = $expl[0];
echo $firstname.' '.$lastname;
I have created a form that has a name and email address input.
Name: John Smith
Email: johnsmith#example.com
What I want to do is split the name in to first name and surname from the posted.
How would I go about doing this?
Assuming you are escaping user input and there is a validation to add space between name.
If that is already not implemented you could implement them otherwise consider to use separate input box for both first name and last name.
$name=explode(" ",$_POST['name']);
echo $name[0]; //first name
echo $name[1];// last name
$user = 'John Smith';
list($name, $surname) = explode(' ', $user);
$name_array = explode(" ",$name);
A quick way is to use explode(). But note that this will only work if there is only one space in it.
$name = "John Smith";
$parts = explode(' ', $name);
$firstName = $parts[0];
$surname = $parts[1];
As i have this:
$full_name = $data['full_name'];
list($firstname, $lastname) = explode(' ', $_POST['full_name']);
(after this comes a query where it inserts $lastname and $firstname)
Where should i use ucfirst() ?
Should i just make new variables again?
$newfirstname = ucfirst($firstname);
$newlastname = ucfirst($lastname);
or can i integrate ucfirst somehow somewhere in the code at top?
list($firstName, $lastName) = array_map('ucfirst', explode(' ', $_POST['full_name']));
array_map will apply the function to all array elements.
If they are proper names you could simply use the ucwords() function on the string.
http://www.php.net/manual/en/function.ucwords.php
I suggest using something like
$full_name = ucwords(strtolower($_POST['full_name']));
your approach
list($firstname, $lastname) = explode(' ', $_POST['full_name']);
doesn't work for names containing more than one space.