Best way to turn a string into 2 variables - php

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;

Related

Split strings with full name into just first name

I know this question has been answered in here before, but the different functions suggested in the other questions have not been to any help for me - and I´ve tried some few.
I have for example this string with three names that outputs from my database every time it's being loaded:
$string = "Joe Hansen, Carl Clarkson Clinton, Miranda Cobweb Fisher-Caine";
I only want it to output:
$string = "Joe, Carl, Miranda";
I tried this one: click - but it only outputs the first name in some situations and not every time. Is there a easy solution to this one? I also tried explode and implode but did not get that to work either.
Something like this?
<?php
$string = "Joe Hansen, Carl Clarkson Clinton, Miranda Cobweb Fisher-Caine";
$names = explode(",", $string);
$firstNames = array_map(function($name) {
$split = explode(" ", trim($name));
return reset($split);
}, $names);
echo implode(", ", $firstNames);
First you can explode() string with comma , separated. Then go through the loop.
and get first name in the array with substr() and then implode with ,.
$string = "Joe Hansen, Carl Clarkson Clinton, Miranda Cobweb Fisher-Caine";
$names = explode(",", $string);
$firstNames = array();
foreach($names as $name){
$firstNames[] = substr(trim($name), 0, strpos(trim($name), " "));
}
echo implode(", ", $firstNames);
First explode the string on ,, loop through the array, then push the elements in a new array and implode it.
$string = "Joe Hansen, Carl Clarkson Clinton, Miranda Cobweb Fisher-Caine";
$new_string=explode(",",$string);
$slipt_arr=explode(" ",$new_string);
$final_arr=array();
foreach ($new_string as $value)
{
$elements=array_filter(explode(" ",$value));
array_push($final_arr,current($elements));
}
echo implode(", ",$final_arr);

Splitting a string from a potential splitter

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;

How to get the value of an array after first index?

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.

PHP split text after space

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];

PHP - get certain word from string

If i have a string like this:
$myString = "input/name/something";
How can i get the name to be echoed? Every string looks like that except that name and something could be different.
so the only thing you know is that :
it starts after input
it separated with forward slashes.
>
$strArray = explode('/',$myString);
$name = $strArray[1];
$something = $strArray[2];
Try this:
$parts = explode('/', $myString);
echo $parts[1];
This will split your string at the slashes and return an array of the parts.
Part 1 is the name.
If you only need "name"
list(, $name, ) = explode('/', $myString);
echo "name is '$name'";
If you want all, then
list($input, $name, $something) = explode('/', $myString);
use the function explode('/') to get an array of array('input', 'name', 'something'). I'm not sure if you mean you have to detect which element is the one you want, but if it's just the second of three, then use that.

Categories