PHP split text after space - php

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

Related

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 a sting if it has a space and detect if its been split

I need to pass two variables with no spaces to a web service so that i dont get an invalid response.
$firstname and $surname
I need to make these variables from a variable called $display_name
Display name may or may not contain a space. It will usually be something like 'Joe Smith' or 'JoeSmith'
So i cant just do (because with 'JoeSmith' I will get no surname)
$pieces = explode(" ", $display_name);
$firstname = $pieces[0]; // Joe
$surname = $pieces[1]; // Smith
likewise i cannot do (because of the potential space)
$firstname = $display_name; // Joe Smith
$surname = $display_name; // Joe Smith
How can i ensure both firstname and surname are populated with no spaces. Even if the display name was 'Joe T Smith'?
if (count($pieces) < 2)
{
// Wasn't split
}
else
{
//Was split into at least two pieces
}
Just use a conditional statement to see if the split was successful, if it was do the first code block, if it wasn't do the second code block

Best way to turn a string into 2 variables

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;

Simple REGEX Question in PHP

I want to take data entered in this format:
John Smith
123 Fake Street
Fake City, 55555
http://website.com
and store the values in variables like so:
$name = 'John Smith';
$address = '123 Fake Street';
$city = 'Fake City';
$zip = '55555';
$website = 'http://website.com';
So first name will be whatever is entered on the first line
address is whatever is on the second line
city is whatever is entered on the third line before the comma seperator
zip is whatever is on the third line after the comma
and website is whatever is on the fifth line
I don't want the pattern rules to be stricter than that. Can someone please show how this can be done?
$data = explode("\n", $input);
$name = $data[0];
$address = $data[1];
$website = $data[3];
$place = explode(',', $data[2]);
$city = $place[0];
$zip = $place[1];
Well, the regex would probably be something like:
([^\r]+)\r([^\r]+)\r([^,]+),\s+?([^\r]+)\r(.+)
Assuming that \r is your newline separator. Of course, it'd be even easier to use something like explode() to split things in to lines...
If you want something more precise, you could use this:
$matches = array();
if (preg_match('/(?P<firstName>.*?)\\r(?P<streetAddress>.*?)\\r(?P<city>.*?)\\,\\s?(?P<zipCode>.*?)\\r(?P<website>.*)\\r/s', $subject, $matches)) {
var_dump( $matches ); // will print an array with the parts
} else {
throw new Exception( 'unable to parse data' );
}
cheers

Categories