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

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.

Related

php indexed array manipulation and filtering

I have an array manipulation/situation that I cannot figure out. In a nutshell:
Get a string such as:
$testString = 'John doe 123 Main st 77555';
I am trying to get things split up to be 3 main parts such as:
$fname = 'John';
$lname = 'doe';
$address = '123 Main st 77555';
Currently I am exploding the array as such:
$splitTestString = explode(" ", $testString");
which gives me the string inside an array.
I've tried a for loop to go through the exploded string:
for($i = 0; $i <= count($splitTestString); $i++) {
$fname = $splitTestString[0];
$lname = $splitTestString[1];
if(is_numeric($splitTestString[2])) { //take into account 2 last names
$newAddress = $splitTestString[2];
} else {
$lname .= ' '.$splitTestString[2];
}
}
But I am not sure how to get the address after the initial numbers all into its own variable. Another string example:
$testString = 'John doe smith 123 main st 77555';
$fname = 'John';
$lname = 'doe smith';
$newAddress = '123 main st 77555';
The user would be instructed to enter the information in the above format of first name, last name, address and zip code.
This is my first question out of all the searches I've done on here and please let me know if I've not followed the rules properly. I'm just at my wits end on this problem and cannot seem to find a solution to this situation. Thanks in advance!
You don't need to do everything in a single loop, you should come up with a process for populating the name variables until you hit a word that starts with a number (is this really a safe assumption though?), then simply join the remainder into the address.
If possible, you should go back to the drawing board and provide a way for the user to provide the information in separate fields.
$testString = 'John doe smith villalobos garcia navarro 123 Main st 77555';
$parts = explode(' ', $testString);
// Don't assume we will always have a first or last name, there could be only an address
$fname = '';
// Set up a buffer for the last name words
$lnameBuffer = [];
// Process input buffer until we hit a part that begins with a number
while(!is_numeric(substr($parts[0], 0, 1)))
{
// Shift the next word off of the buffer
$currPart = array_shift($parts);
/*
* If we don't have a first name yet, set it
* Otherwise, append the word to the last name buffer
*/
if(empty($fname))
{
$fname = $currPart;
}
else
{
$lnameBuffer[] = $currPart;
}
}
// Join the last name buffer to populate the $lname variable
$lname = implode(' ', $lnameBuffer);
// The rest of the input buffer contains the address
$newAddress = implode(' ', $parts);
echo 'fname: '.$fname.PHP_EOL;
echo 'lname: '.$lname.PHP_EOL;
echo 'newAddress: '.$newAddress.PHP_EOL;
You could however achieve this much more easily using regex.
$testString = 'John doe smith villalobos garcia navarro 123 Main st 77555';
preg_match('/([^\s]\S+)\s([^\d]*)(.*)/', $testString, $matches);
$fname = $matches[1];
$lname = $matches[2];
$newAddress = $matches[3];
echo 'fname: '.$fname.PHP_EOL;
echo 'lname: '.$lname.PHP_EOL;
echo 'newAddress: '.$newAddress.PHP_EOL;
If your string is always formatted like "firstname lastname everything else is the address" you can just pass explode a limit like so:
$str = 'John doe 123 Main st 77555';
$parts = explode(' ', $str, 3);
var_dump($parts);
//array(3) {
// [0]=>
// string(4) "John"
// [1]=>
// string(3) "doe"
// [2]=>
// string(17) "123 Main st 77555"
//}
If you need to split with a rule like 'the first time we see a number indicates the start of an address' you can just find that and split the string up like so:
$str = 'john doe smith 123 fake street paris france';
$matches = [];
preg_match('/[0-9]/', $str, $matches, PREG_OFFSET_CAPTURE);
$numberPosition = $matches[0][1]; // this is the first matching element, and its position
$left = trim(substr($str, 0, $numberPosition)); // left side of the found number
$right = trim(substr($str, $numberPosition)); // right side of the found number
var_dump([
$left, $right
]);
//array(2) {
// [0]=>
// string(20) "john doe smith"
// [1]=>
// string(26) "123 fake street paris france"
//}

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;

Split string First and Lastname (Capitals and Lowercase)

<?php
$string1 = "FARMER John";
$string2 = "OVERMARS DE Rafa";
$string3 = "VAN DER BELT Dick";
?>
To save the first and lastname in a mysql database I need to split the string.
Above you can see a few examples.
What is the best way to split this string, note that the lastname is in caps.
Result should be:
ResultString1: John FARMER
ResultString2: Rafa OVERMARS DE
ResultString3: Dick VAN DER BELT
This is a really bad idea.
There are tons of things that can go wrong if you're purely relying on letter case to signify something. And saving it all in another string just perpetuates the problem.
That said, you can mitigate (a small amount of) the badness by storing the new values separately, so as not to pass along unstructured information to the next unfortunate person who has to maintain your database. This code does that, while also allowing for multi-word first names (like "John Paul" or such).
I also made it handle these in array form, since I assume that you probably want to handle more than three names.
<?php
$string1 = "FARMER John";
$string2 = "OVERMARS DE Rafa Dafa";
$string3 = "VAN DER BELT Dick";
$strings = array(array('orig'=>$string1), array('orig'=>$string2), array('orig'=>$string3));
foreach($strings as $key=>$val){
$oldwords = explode(' ',$val['orig']);
foreach($oldwords as $word){
if(preg_match('/[a-z]/',$word)){
$firstname .= " ".$word;
}else{
$lastname .= " ".$word;
}
}
$firstname = trim($firstname);
$lastname = trim($lastname);
$strings[$key]['newfirst'] = $firstname;
$strings[$key]['newlast'] = $lastname;
$firstname = "";
$lastname = "";
}
print_r($strings);
?>
Follow the following steps:
Convert string to array when space appears.
Pop out the last array element(apparently the first name) using array_pop.
Insert the popped out name in front using array_unshift
Convert array back to string.
$string3 = "VAN DER BELT Dick";
$arr = explode(" ", $string3);
array_unshift($arr, array_pop($arr));
echo implode(" ", $arr); // Dick VAN DER BELT
$arr = explode(" ", $string3);
$last_word = array_pop($arr);
$final_string = ucfirst($last_word)." ".strtoupper(implode(" ", $arr));
echo $final_string;
As others said, your problem description is rather vague. However with a fixed pattern like this, you could very well split the names via a regular expression (given the surname is always in uppercase):
<?php
$strings = array("FARMER John", "OVERMARS DE Rafa", "VAN DER BELT Dick");
$regex = '~^([A-Z ]+\b)(\w+)$~';
foreach ($strings as $string) {
if(preg_match($regex, $string, $match)) {
$surname = trim($match[1]);
$forename = trim($match[2]);
echo "Surname: $surname, Forename: $forename\n";
}
}
?>
See a working demo on ideone.com (plus the one on regex101.com).

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;

Categories