PHP: Make first letter capital in list? - php

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.

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;

PHP How to parse a string and conver to variables

Using PHP, I am looking to parse a string and convert it into variables. Specifically, the string will be a file name, and I'm looking to break the file name into variables. Files are nature photos, and have a uniform format:
species_name-date-locationcode-city
All files names have this exact format, and the "-" is the delimiter. (I can make it whatever if necessary)
an example of the file name is common_daisy-20130731-ABCD-Dallas
I want to break it up into variables for $speciesname, $date, $locationcode, $city.
Any idea on how this can be done? I have seen functions for parsing strings, but they usually take the form of having the name of the variable in the string, (For example "species=daisy&date=20130731&location=ABCD&city=Dallas") which I don't have, and cannot make my file names match that. If I wanted to use a string replace to change the delimiters to variables= I would have to use 4 different delimiters in the filename and that wont work for me.
Thanks for anyone who tries to help me with this issue.
list($speciesname, $date, $locationcode, $city) = explode('-', $filename);
Use PHP explode
$pieces = explode('-', 'species_name-date-locationcode-city');
$name = $pieces[0];
$data = $pieces[1];
$code = $pieces[2];
$city = $pieces[3];
<?php
$myvar = 'common_daisy-20130731-ABCD-Dallas';
$tab = explode ('-', $myvar);
$speciesname = $tab[0];
$date = $tab[1];
$locationcode = $tab[2];
$city = $tab[3];
?>
You can explode the string on delimiter and then assign to variables
$filename = 'species_name-date-locationcode-city';
$array = explode('-', $filename);
$speciesname = $array[0];
$date = $array[1];
$locationcode = $array[2];
$city = $array[3];
http://php.net/manual/en/function.explode.php
$pieces = explode("-", $description);

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;

PHP: undefined offset in explode()

I have this:
list($firstname, $lastname) = explode(' ', $queryString);
Sometiems $lastname does not gets defined, and it's there i am getting undefined offset error.
Because it can not find anything to put in $lastname, i guess.
After the explode() i have:
if(!$lastname) { $lastname = $firstname; }
So my question is how can i define it as the $firstname if $lastname is not defined (if you wrote only 'Adam' and not 'Adam Thompson', the lastname should be defined so it is 'Adam Adam')
It does this for me now, but I am receiving the offset error
list($firstname, $lastname) = array_pad(explode(' ', $queryString, 2), 2, null);
The 2 in explode() ensures, that there are at most 2 values and array_pad() ensures, that there are at least 2 values. If there is no space character , $lastname is null. This you can use to decide what comes next
$lastname = is_null($lastname) ? $firstname : $lastname;
Little update: For this specific case you can use a little trick
list($firstname, $lastname) = array_pad(explode(' ', $queryString, 2), 2, $queryString);
This will do all that in one step. It should work, because
There is always at least one value (for $firstname)
If there is one value, then $queryString == $firstname. Thats now the value that is used to fill the array up to 2 values (which is exactly one, because one value we already have)
If there are two values, then the array is not filled with $queryString, because we already have 2 values
At least for readability I would prefer the first more obvious solution.
Try appending a space:
list($firstname, $lastname) = explode(' ', $queryString . ' ' );
shouldn't have to change a thing after that.
You're not getting an Error, but a Notice.
Although this is acceptable since PHP is a dynamic language, you can prevent it with isset():
if(!isset($lastname)) {
$lastname = $firstname;
}
UPDATE
Per the comments, list() is the culprit for the Notice. In which case, I wouldn't recommend the use of list() when explode() doesn't yield the appropriate number of parameters.
If you must, the answer by brady or undefined offset when using php explode() can work. Although it's pretty ugly in my opinion. I believe your code would be much more intuitive if you just did the following:
$name = explode(' ', $queryString);
if (isset($name[1])) {
// show lastname
}
else {
// show firstname
}
I just ran into this today. my solution was not the above,
(which had no effect) mine was the following:
while (!feof($fh))
{
$line = fgets($fh);
print $line;
}
instead of doing:
while ($line = fgets($fh))
{
print $line;
}
I'm not clear why this works, but the notice will go away. First, with this code I get the undefined offset notice:
list($month, $day, $year)=explode('-', $dateToChange, 3);
However, with this code, I don't:
list($month, $day, $year, $junk)=explode('-', $dateToChange.'---', 4);
Also note, with '-' or '--' appended to $dateToChange, I will get the offset notice. It takes three dashes for it to go away in my example with four variables. $junk contains the two dashes (one being a separator).

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