PHP: Separate one field in two - php

As many recommend me to separate firstname and lastname instead of "full_name" with everything in, how can I separate them to each variables, so if for you example type in the field: "Dude Jackson" then "Dude" gets in $firstname and Jackson in the $lastname.

It's impossible to do with 100% accuracy, since the first/last name contains more information than a single "full name". (A full name can include middle names, initials, titles and more, in many different orders.)
If you just need a quick fix for a legacy database, it might be OK to split by the first space.

Assuming first name always comes first and there's no middle name:
list($firstname, $lastname) = explode(' ', $full_name);
This simply explodes $full_name into an array containing two strings if they're separated by only one space, and maps them to the first and last name variables respectively.

You can do:
list($first_name,$last_name) = explode(' ',$full_name);
This assumes that you full name contains first name and last name separated by single space.
EDIT:
In case the lastname is not present, the above method give a warning of undefined offset. To overcome this you can use the alternative method of:
if(preg_match('/^(\S*)\s*(\S*)$/',$full_name,$m)) {
$first_name = $m[1];
$last_name = $m[2];
}

$full_name = "Dude Jackson";
$a = explode($full_name, " ");
$firstname = $a[0];
$lastname = $a[1];

you would need to explode the value into its parts using a space as the separator
http://php.net/manual/en/function.explode.php

I am no PHP programmer, but for a quick fix, without data loss,
$full_name = "Dude Jackson";
$a = explode($full_name, " ");
$firstname = $a[0];
$count = 1;
$lastname = "";
do {
$lastname .= $a[$count]." ";
$count++;
} while($count<count($a));
$lastname = trim($lastname);
This should save all remaining part of name in $lastname, should be helpful for names like "Roelof van der Merwe". Also you can throw in checks for $full_name as first name only, without last name.

This is the code/solution
$full_name = "Dude Jackson";
$a = explode($full_name, " ",1);
if(count($a) == 2)
{
$firstname = $a[0];
$lastname = $a[1];
}
if(count($a) < 2)
{
$firstname = $full_name;
$lastname = " ";
}

Related

Last name usort

I asked a similar question but still having issues when some aspects.
The way this php file is working is that a persons name is being stored in the database in the names cell, in the format John Doe(firstname lastname). So I've separated the name with this code, so surname, firstname:
foreach ($customer_names as $key => $value) {
$parts = explode(" ", $value->name);
$lastname = array_pop($parts);
$firstname = implode(" ", $parts);
$name = $lastname.", ".$firstname." ";
echo "<option value='$value->name'>$name </option>";
now that gives me a list of names like Doe, John.
However, I need to sort the names in order of the surname.
using usort. How would I do that? I've tried playing around with the code, but still is showing up in the order of the first name (set by the db query).
Still a bit new to usort functionality.
This should work:
usort($customer_names, function($customer1, $customer2) {
return strcmp(
substr($customer1->name, strrpos($customer1->name, " ")),
substr($customer2->name, strrpos($customer2->name, " "))
);
});
Your $customer_names array will then be sorted by the last name of the customer. Last name means the string after the last space, e.g. John Doe would be Doe. Mary Lou Foo would be Foo.
Please refer to http://php.net to learn more about the used functions.
//Program for sorting list of names according to last name
<?php
class array_sort
{
public $temp;
public function alhsort(array $sorted)
{
for($i=0; $i<count($sorted)-1; $i++){
for($j=$i+1; $j<count($sorted); $j++){
if(strcasecmp(end(explode(' ', $sorted[$i])), end(explode(' ', $sorted[$j])))>0){
$temp = $sorted[$i];
$sorted[$i] = $sorted[$j];
$sorted[$j] = $temp;
}
}
}
return $sorted;
}
}
$sortarray = new array_sort();
print_r($sortarray->alhsort(array('Ayush Jain', 'Abhishek Gupta', 'Rahul Rajput', 'Kapil Patel', 'Shobit Shrivastav', 'Hitesh Gupta')));
?>

PHP processing large form

I am having difficulty in saving all post data to csv file and emailing the values to an address. I have over 125 post variables and im quite stuck. Here is a sample of my code thus far:
<?php
$x23 = "date";
$x24 = "fclose";
$x25 = "fopen";
$x26 = "fwrite";
$x27 = "mail";
$x28 = "time";
extract($_POST);
$a1 = $_POST['fname'];
$a2 = $_POST['lname'];
$a3 = $_POST['email'];
$a4 = $_POST['landline'];
$a5 = $_POST['mobile'];
$a6 = $_POST['addr1'];
$a7 = $_POST['addr2'];
$a8 = $_POST['towncity'];
$a9 = $_POST['postcode'];
$x1d = $a1 . "," . $a2 . "," . $a3 . "," . $a4 . "," . $a4 . "," . $a5 . "," . $a6 . "," . $a7 . "," . $a8 . "," . $a9 . "
";
$quotation = $x25("file5.csv", "a");
$x26($x1d, $quotation);
$x24($x1d);
header('Location: mydomain.co');
$x20 = 'mail#mydomain.com';
$x22 = 'Quotation - My Company';
$x27($x20, $x21, $x23, $x1f);
?>
I have not put all variables in this question (not sure how to do this, but I think fputcsv() would do the job, to save all the 125 variables being written, but Iv'e never much used PHP and not sure on arrays and fputcsv()).
How would I loop through all my post variables and append them to csv as one row?
Any help would be appreciated.
The function you're looking for is implode. It implodes an array into a single string with a specific "glue", in this case ','.
So, the simplest way is to use implode(',', $_POST), but in case not all of the values are supposed to be used, there's a nice way to handle it by changing the names of the form elements.
In the form, if you change the name from "fname" into "data[fname]" and do the same for the rest of the elements, then $_POST['data'] will be an array that holds all of the values. Then using implode(',', $_POST['data']) will make sure only desired values are used.
You first of all need to be disciplined about solving one problem at a time.
(1) Create the CSV data in a variable
(2) Write the data to a file
(3) Send an email
(4) Include an attachment in the email
Or even break it down into more steps. Trying to solve a bunch of problems all at once is only going to get yourself more confused, especially if you are just getting started on programming.
So let's solve the "create the CSV" file.
You can easily loop through your $_POST and create a CSV file like this:
$csv_line = '';
$sep = ''; // don't put a comma before the 1st element
foreach ($_POST as $k -> $v) {
$csv_line .= $sep . "\"$v\"";
$sep = ','; // put a comma before the 2nd, 3rd, etc. elements
}
However, there are at least 2 problems with this. You may not want EVERY element in your $_POST to be put into the CSV, and there is no guarantee of the order those elements within $_POST.
So we'll create a separate array with just the fields we are interested in and making sure they are in the order we want to keep it:
$myFields = array('email',
'fname',
'lname',
'junk',
...);
$csv_line = '';
$sep = ''; // don't put a comma before the 1st element
foreach ($myFields as $k) {
$csv_line .= $sep . "\"$_POST[$k]\"";
$sep = ','; // put a comma before the 2nd, 3rd, etc. elements
}
Now all you have to do is write out that line into a file, figure out how to send an email, and figure out how to attach the file to the email. But at least you are one step closer...

How Can I Extract the stringlength higher word in an array?

In the first time, I'm sorry for my disastrous english.
After three days trying to solve this, i give up.
Giving this array:
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" )
I have to extract the full name of the higher first stringlength word of each full name.
In this case, considering this condition Benjamin will be the higher name. Once
this name extracted, I have to print the full name.
Any ideas ? Thanks
How about this?
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" );
if (count($names) > 0)
{
$higher_score = 0;
foreach ($names as $name_key => $name_value)
{
$name_array = explode(" ", $name_value);
// echo("<br><b>name_array -></b><pre><font FACE='arial' size='-1'>"); print_r($name_array); echo("</font></pre><br>");
$first_name = $name_array[0];
// echo "first_name -> ".$first_name."<br>";
$score = strlen($first_name);
// echo "score -> ".$score."<br>";
if ($score > $higher_score)
{
$higher_score = $score;
$winner_key = $name_key; }
}
reset($names);
}
echo("longest first name is ".$names[$winner_key]." with ".$higher_score." letters.");
As said before, you can use array_map to get all the lenghts of the first strings, and then get the name based on the key of that value.
$names = array ( "James Walter Case", "Benjamin Wallace Pinkman", "Billy Elliot Newson" );
$x = array_map(
function ($a) {
$x = explode (" ", $a); // split the string
return strlen($x[0]); // get the first name
}
, $names);
$maxs = array_keys($x, max($x)); // get the max values (may have equals)
echo $names[$maxs[0]]; // get the first max
-- EDIT
Actually, there is a better way of doing this, considering this case. You can simply order the array by the lenght of the first names, and then get the first key:
usort($names,
function ($a, $b) {
$aa = explode(" ", $a); // split full name
$bb = explode(" ", $b); // split full name
if (strlen($aa[0]) > strlen($bb[0])){
return 0; // if a > b, return 0
} else {
return 1; // else return 1
}
}
);
echo $names[0]; // get top element
Allow me to provide a handmade solution.
<?php
$maxLength = 0;
$fullName = "";
$parts = array();
foreach($names as $name){
/* Exploding the name into parts.
* For instance, "James Walter Case" results in the following array :
* array("James", "Walter", "Case") */
$parts = explode(' ', $name);
if(strlen($parts[0]) > $maxLength){ // Compare first length to the maximum.
$maxLength = strlen($parts[0]);
$fullName = $name;
}
}
echo "Longest first name belongs to " . $fullName . " (" . $maxLength . " character(s))";
?>
Basically, we iterate over the array, split each name into parts (delimited by spaces), and try to find the maximum length among first parts of names ($parts[0]). This is basically a maximum search algorithm.
There may be better ways with PHP array_* functions, but well, this one gets pretty self-explanatory.
You can try something like..
$maxWordLength=0;
$maxWordIndex=null;
foreach ($names as $index=>$name){
$firstName=first(explode(' ',$name));
if (strlen($firstName)>maxWordLength){
$maxWordLength=strlen($firstName);
$maxWordIndex=$index;
}
}
if ($maxWordIndex){
echo $names[$maxWordIndex];
}

concatenating array elements between first and last dynamically in php

i have searched on the Internet but i couldn't find a solution, i have got a string which contain names(two, three,..) of a staff.
i want to extract from this string the first name, middle names and last name
sample string
$name = "Michael O. A. Ndanshau";
I am using explode function to get the names
$exp =explode(" ",$name);
print_r($exp);
array output
Array
(
[0] => Michael
[1] => O.
[2] => A.
[3] => Ndanshau
)
from above array i can get the first name and last name
$fname = $exp[0];
$lname = end($exp);
am not sure how to get the middle name as it may be dynamic.
my target is to concatenate what is between the first element and the last as the middle name
if a have n elements in the array
$middename = $exp[1]+..$exp[n-1];
any help please?
Get the first element of the array to get the first name and last element to get the last name. Get everything between for the middle name:
$firstname = $parts[0];
$middlename = implode(array_slice($parts, 1, -1));
$lastname = end($parts);
var_dump($firstname, $middlename, $lastname);
Output:
string(7) "Michael"
string(4) "O.A."
string(8) "Ndanshau"
Demo
if(count($arr)>2) {
$middleName = implode(' ',array_slice($arr,1,count($arr)-2));
}
else {
$middleName = '';
}
Maybe something like this. array_shift and array_pop modify the array so all that is left is the element(s) for the middle name:
$fname = array_shift($exp);
$lname = array_pop($exp);
middlename = implode(' ', $exp);
But you might want to check to make sure there are more than 2 elements up front, or at least 1 remaining:
$fname = array_shift($exp);
$lname = array_pop($exp);
if(count($exp) >= 1) {
middlename = implode(' ', $exp);
}
Or something similar.

Swapping two variables with RegEx

So here is my code, and then I will explain what I am having trouble with:
foreach($people as $person){
// counter for each person
$counter = 0;
// get variables for each item
list($fullName,$phoneNumber,$address,$birthday,$salary) = explode(':', $person);
// get variables for first and last name
list($firstName, $lastName) = explode(" ", $fullName);
// get variables for phone numbers
list($areaCode, $middleDigits, $lastDigits) = explode('-',$phoneNumber);
//get variables for address
list($street,$city,$statezip) = explode(", ", $address);
// get variables for state and zip separately
list($state,$zipCode) = explode(" ", $statezip);
// print file with the first and last names reversed
$tempFName = $firstName;
$tempLName = $lastName;
echo $newPerson = (preg_replace("/($tempLName)($tempFName)/", $firstName, $lastName, $person))."<br/>";
$counter++;
}
What I want to do, is print the original $person, but with the $firstName and $lastName 's reversed. I'm able to replace the values and then print out each variable, but then it wouldn't have the same format as $person originally did unless I formatted each line. I was wondering if there was a way to do it without formatting each output to look identical to the original $person variable.
Thanks!
It looks as if Firstname and Lastname are always separated by whitespace and preceed the first colon character... if this is correct the above may be overkill. Try this:
echo $newPerson = (preg_replace("/(.*?)\s+(.*?)\:/", '$2,$1:', $person))."<br/>";

Categories