I have an array with SURNAME NAME as value. I would need to invert that, getting NAME SURNAME as result. I've been taking a look at php functions but couldn't find a useful one. Thank you!
$name = array('SMITH JOHN', 'BACON KEVIN', 'MERCURY FREDDIE');
Try this code:
$names = array('SMITH JOHN', 'BACON KEVIN', 'MERCURY FREDDIE');
foreach ($names as &$full_name){ //Remember here to pass by reference &
$parts = explode(" ", $full_name);
$full_name = "{$parts[1]} {$parts[0]}" ;
}
var_dump($names) ;
This should work:
$names = preg_replace('/^(\S+)\s+(\S+)$/', '\2 \1', $names);
edit: Yep, it works just fine.
Please note that this only works for two-part names. If it has more than two parts (e.g. middle name, suffix) it will leave it as-is.
$name = array('SMITH JOHN', 'BACON KEVIN', 'MERCURY FREDDIE');
array_walk(
$name,
function (&$value) {
$value = implode(' ',array_reverse(explode(' ',$value)));
}
);
As Jan pointed out, string parsing is the way to go (take the individual string and parse the parts to compose the new string) but just be warned in general you'll need to make assumptions about the names to do this correctly.
If you're guaranteed to have only LAST FIRST entries, you're fine.
But for example, what about names like
HENRY VAN WINKLE
MADONNA
CATHERINE ZETA-JONES
ROBERT DOWNEY JR.
MR. T
Some cases are clear, but others aren't.
Related
How can I get the 800-555 from this 800-555-5555 with explode()?
Here is a good example:
$rawPhoneNumber = "800-555-5555";
$phoneChunks = explode("-", $rawPhoneNumber);
First chunk = $phoneChunks[0]; //800
Second chunk = $phoneChunks[1]; //555
Third Chunk chunk = $phoneChunks[2]; //5555
But how can I get the 800-555?
Okay, I see, here need more comment... So, this is only an example... In real I add a word (now $word) to string delimiter and my string is a full article... I want that, if this word second time published in the article, with str_word_count() will count, how many characters was in the text to the second (or third, if I want that) $word...
So I want that, I get the string from the second "hit" to back.
Okay, here is a more obvious example:
$text = oh my god, thank you the lot of downvotes, geniuses *.*
$explode = explode(",", $text);
$whatiwant = $explode?? // I WANT THE STRING FROM THE SECOND "," TO BACK
So I want that $whatiwant = oh my god, thank you the lot of downvotes
Implode, explode and array_slice.
I use array_slice because that makes the function more dynamic.
Now you can just set the $items to get the number of items you want.
If you set a negative value it counts backwards.
$delim = ",";
$items =2;
$text = "oh my god, thank you the lot of downvotes, geniuses *.*";
$whatiwant = implode($delim, array_slice(explode($delim, $text),0,$items));
Echo $whatiwant;
https://3v4l.org/KNSC4
You could also have an start variable to make the start position dynamic.
https://3v4l.org/XD0NV
Doing concatenation of already generated array's indexes is the simple way for you.
Sample Code
echo $phoneChunks[0]."-".$phoneChunks[1];
This is working for me:
$rawPhoneNumber = "800-555-5555";
$phoneChunks = explode("-", $rawPhoneNumber);
$first_chunk = $phoneChunks[0]; //800
$second_chunk = $phoneChunks[1]; //555
$third_chunk_chunk = $phoneChunks[2]; //5555
$portion_array = array($first_chunk, $second_chunk);
echo implode("-",$portion_array);
Output:
800-555
How do I modify the last element in an array?
The array looks like this:
$fields = array("firstName = 'Bob', ",
"lastName = 'Smith', ",
"email = 'bob#example.com', ",
"address = '123 anystreet', ");
The array is generated by a script which creates the values and adds the comma/space at the end of each string. I want to remove that comma/space from only the last element in that array. Keep in mind that the values could in fact contain a comma/space combination so only the last element and the last two characters of the last element need to be removed.
I've looked at the end() function but I don't think that is going to help since it just gets the value.
Edit Ok so I created this function/array so that I would only have one mysql function to update users. Sort of like a detect changes function and it only passes back the required/changed fields. I didn't realize there were problems associated with this approach. I thought that since I already had the mysql queries written in my old functions there shouldn't be an issue with this way. The file that it's in will not be accessible to the public. I'm going to use the best answer that works for me but I'm going to search for why this is problematic and I would appreciate comments/links as to what is wrong with this approach.
Like this!
end($array);
$key = key($array);
reset($array);
There's a shorthand way to do this, but it's easier to follow if it's broken out into pieces:
$index = count( $fields ) - 1;
$value = $fields[$index];
$fields[$index] = preg_replace( "/,\ $/", "", $value );
To change the value of the last numeric element:
$lastValue = array_pop($fields);
$fields[] = rtrim(', ',$lastValue);
If you are preparing these values for a query I would suggest storing everything without commas in an array then calling implode on that array when needed to prevent trailing comma problems
Array pop and push are the easiest way to do it for basic arrays. (I know that isn't technically the question but many people will come here looking for the answer in relation to simple arrays as well).
<?php
function update_last(&$array, $value){
array_pop($array);
array_push($array, $value);
}
?>
Then you can use the function like this:
<?php
$array = [1,2,3];
update_last($array, 4); //$array = [1,2,4];
?>
There are few ways:
1) For associative arrays, if you don't know the last element key, you better find the last element key first and change its value.
$array[end((array_keys($array)))] .= ' additional text';
2) if you don't know and don't care about keys, you can cut the last element and create a new one.
$array[] = array_pop($array).' additional text';
The last element of an array can always be retrieved using array_pop(), no matter how the array is indexed. It will also remove that element from the array, which is very useful if we want to modify and then add it again, as you cannot modify the element in-place.
What you are trying to do can be done with a simple, single line of code:
$fields[] = preg_replace("/, $/", "", array_pop($fields));
That's it. Here's what it does:
preg_replace() searches for a Regex pattern in a string and if found, replaces the match with an alternative string.
The pattern we search for is /, $/, which means: Match for ", " (comma + space) but only if it is at the very end of the string ($).
The replacement string is simply an empty string (""), thus the match is just deleted from the string.
The string we want to perform that replacement on is array_pop($fields), the last element of the array $fields, which is also removed from that array.
The modified string is then re-added to the array at the end ($fields[] = adds an element to an array without an explicit key and makes it the new last element).
Let's test it:
$fields = array(
"firstName = 'Bob', ",
"lastName = 'Smith', ",
"email = 'bob#example.com', ",
"address = '123 anystreet', ");
print "Before:\n\n";
print_r($fields);
$fields[] = preg_replace("/, $/", "", array_pop($fields));
print "\nAfter:\n\n";
print_r($fields);
Output:
Before:
Array
(
[0] => firstName = 'Bob',
[1] => lastName = 'Smith',
[2] => email = 'bob#example.com',
[3] => address = '123 anystreet',
)
After:
Array
(
[0] => firstName = 'Bob',
[1] => lastName = 'Smith',
[2] => email = 'bob#example.com',
[3] => address = '123 anystreet'
)
Note how the last comma is gone? Just try it yourself.
stumbled upon this today. i think the easiest non-pointer-breaking way would be:
array_splice($array, -1, 1, strtolower(end(array_values($array))).'blah' );
of course you can drop array_values if you dont have to care for the pointer.
but i wonder if this is a good way, since the extract-n-replace-stuff of splice could be more demanding than a pop or sth?
PHP 7 >= 7.3.0
$array[array_key_last($array)] = 'new value';
Demo
$fields = array(
"firstName = 'Bob', ",
"lastName = 'Smith', ",
"email = 'bob#example.com', ",
"address = '123 anystreet', "
);
$last = $fields[array_key_last($fields)];
$last = preg_replace( "/, $/", "", $last);
$fields[array_key_last($fields)] = $last;
I think PHP's Implode function might be a good alternative, instead of generating the commas yourself.
Barring that, you would have to use something like:
$lastfield = $fields[count($fields)-1];
$lastfield = str_split($lastfield,strlen($lastfield)-2);
$fields[count($fields)-1] = $lastfield;
The first and third lines are included to make the second line easier to read, but this could easily be compounded to one line.
Would appreciate any help with this.:)
I have the following text file:
roomA Springer, Jerry js#email.com
roomB Cruise, Tom tc#email.com
roomC Jovi, Bon bj#email.com
and I want to sort it by the surname so it outputs:
Cruise, Tom roomB tc#email.com
Jovi, Bon roomC bj#email.com
Springer, Jerry roomA js#email.com
I know how to load the file:
$a = file("details.txt");
and think I have to use explode() to split up the data (tab-seperated):
$array = explode("\t", $a);
this makes the name the second element in the array.
How do I put the string back together with the name coming first, followed by the room and email?
Thanks.
Do a var_dump($array) and it will display you the indexes. You then only need to swap two elements with each other. Here is a trick:
list($array[0], $array[1]) = array($array[1], $array[0]);
After that, you can implode the result as you did explode it:
$line = implode("\t", $array);
Hope this is helpful. Ah well, and for sorting, take a look at array_multisort.
PHP isn't the best tool for this job.
awk -F"\t" '{print $2"\t"$1"\t"$3}' infile | sort > outfile
your data is not in a know format that i know .. the tabs and space between them are not constant ;
* Do not use in production .. i had to hack my way around *
Try
$note = "roomA Springer, Jerry js#email.com
roomB Cruise, Tom tc#email.com
roomC Jovi, Bon bj#email.com";
$data = array();
$info = explode("\n", $note);
echo"<pre>" ;
foreach($info as $line)
{
$words = preg_split("/\\s/", $line);
$words = array_filter($words); // remove spaces
$words = array_values($words); // To reset the keys
$data[$words[1] . $words[2]] = $words[1] . $words[2] ."\t" . trim($words[0]) . "\t" . trim($words[3]) . "\n";
}
asort($data); //Sorting the data ;
print_r(array_values($data));
Output
Array
(
[0] => Cruise,Tom roomB tc#email.com
[1] => Jovi,Bon roomC bj#email.com
[2] => Springer,Jerry roomA js#email.com
)
Advice
Use standard formats suvh as csv, json or xml
I would try improving it with preg_match
I have a string $employee="Mr vinay HS,engineer,Bangalore";. i want to store Mr vinay H S in $name ,engineer in $job and Bangalore in $location. how to do this
$record = explode(",",$employee);
$name = $record[0];
$job = $record[1];
$location = $record[2];
Use the list function to take the exploded array into 3 variables
list($name, $job, $location) = explode(',', $employee);
list($name,$job,$location) = explode(',',$employee);
Note: this will obviously only work if the string is in the format you specified. If you have any extra commas, or too few, then you'll have problems.
It's also worth pointing out that PHP has dedicated functions for handling CSV formatted data.
See the manual page for str_getcsv for more info.
While explode() is the quickest and easiest way to do it, using str_getcsv() rather than simple explode() will allow you to handle input more complex input, eg containing quoted strings, etc.
explode will do just that I guess
http://php.net/manual/en/function.explode.php
Any more help on this would suffer from givemethecode-ism, so I leave you to it ;-)
list($name,$job,$location) = explode(',',$employee);
Something like the following should work:
//The employee name
$employee= "Mr vinay HS,engineer,Bangalore";
//Breaks each portion of the employee's name up
list($name, $job, $location) = explode(',',$employee);
//Outputs the employee's credentials
echo "Name: $name; Job: $job; Location: $location";
Or you can use another function to do that - http://php.net/manual/en/function.str-getcsv.php
list($name,$job,$location) = str_getcsv($employee);
You can look at the explode() and list() functions:
list($name, $job, $location) = explode(",", $employee);
Hey all. I have a string of names separated by commas. I'm exploding this string of names into an array of names with the comma as the delimiter. I need a RegEx to remove a white space(if any) only after the comma and not the white space between the first and last name.
So as an example:
$nameStr = "Sponge Bob,Bart Simpson, Ralph Kramden,Uncle Scrooge,Mickey Mouse";
See the space before Ralph Kramden? I need to have that space removed and not the space between the names. And I need to have any other spaces before names that would occur removed as well.
P.S.: I've noticed an interesting behavior regarding white space and this situation. Take the following example:
When not line breaking an echo like so:
$nameStr = "Sponge Bob,Bart Simpson, Ralph Kramden,Uncle Scrooge,Mickey Mouse";
$nameArray = explode(",", $nameStr);
foreach($nameArray as $value)
{
echo $value;
}
The result is: Sponge BobBart Simpson Ralph KramdenUncle ScroogeMickey Mouse
Notice the white space still there before Ralph Kramden
However, when line breaking the above echo like so:
echo $value . "<br />";
The output is:
Sponge Bob
Bart Simpson
Ralph Kramden
Uncle Scrooge
Mickey Mouse
And all of the names line up with what appears to be no white space before the name.
So what exactly is PHP's behavior regarding a white space at the start of a string?
Cheers all. Thanks for replies.
What's with today's fixation on using regexp to solve every little problem
$nameStr = "Sponge Bob,Bart Simpson, Ralph Kramden,Uncle Scrooge,Mickey Mouse";
$nameArray = explode(",", $nameStr);
foreach($nameArray as $value)
{
echo trim($value);
}
EDIT
PHP's behaviour re white space is to treat it as the appropriate character and do what it's told by you.
HTML's behaviour (or at least that of web browsers) is rather different... and you'll need to learn and understand that difference
Try
$nameStr = preg_replace("/,([\s])+/",",",$nameStr);
$nameArray = explode(",", $nameStr);
This is a workable regex solution, but as others have pointed out above, a simple trim() will do the job with what you already have.
As you have mentioned to remove White Space only after the Comma, considering that space before comma can be left.
You can also use below:
$nameStr = "Sponge Bob, Bart Simpson, Ralph Kramden,Uncle Scrooge,Mickey Mouse";
while (strpos($nameStr, ', ') !== FALSE) {
$nameStr = str_replace(', ', ',', $nameStr);
}
echo $nameStr;
After this, you can simply explode it as:
$allNames = explode(',', $nameStr);
Otherwise the regex by Michael is very good.
Why don't you just preg_split?
$names = preg_split('~,\s*~', $names);
PHP couldn't care less what's in a string, unless it's parsing it for variable interpolation. A space is like any other character, an ascii or unicode value that just happens to show up as a "blank".
How are you replacing those post-comma spaces?
$str = str_replace(', ', ',', $str);
^--space
If that's not catching the space before your Ralph name, then most likely whatever's there isn't a space character (ascii 32). You can try displaying what it is with:
echo ord(substr($nameArray['index of Ralph here'], 0, 1));
Have you tried it with the trim function?
$nameStr = "Sponge Bob,Bart Simpson, Ralph Kramden,Uncle Scrooge,Mickey Mouse";
$nameArray = explode(",", $nameStr);
for($i = 0; $i < count($nameArray); $i++) {
$nameArray[$i] = trim($nameArray[$i];
}
$newNameStr = implode(',', $nameArray);
You can do this with a RegExp, but since it looks like you aren't very experienced with RegExp you shouldn't use them, because when doing it wrong they cost a good chunk of performance.
An easy solution is to avoid using regex and apply the trim function:
$nameStr = 'Bart Simpson, Lisa Simpson,Homer Simpson, Madonna';
$names = explode(',', $nameStr);
foreach($names as &$name) {
$name = trim($name);
}
//this also doesn't falter when a name is only one word
this one works for me
$string = "test1, test2, test3, test4, , ,";
array_map('trim', array_filter(explode(',', $string), 'trim'))
output
=> [
"test1",
"test2",
"test3",
"test4",
]