Jump to content

Archived

This topic is now archived and is closed to further replies.

micah1701

Take spaces out of comma seperated list

Recommended Posts

the user submits a list of keywords, each seperated by a comma.
I want to alphabitize the list and take the spaces out between the keywords.

here's what I'm doing:[code]<?php
$postedList = $_POST['keywords']; // "Cranberry, Banana, Apple"
$keywords = explode(",",$postedList); //create array

foreach($keywords as $keyword){
$keyword = trim($keyword); //remove spaces from each value in array
}
sort($keywords);  //sort the array alphabetically
$data = implode(",",$keywords); //turn the array back into a list

echo $data; //returns:  " Apple, Banana,Cranberry" (with spaces) ???
?>[/code]

it still has spaces? What am I missing?

Share this post


Link to post
Share on other sites
trim only removes spaces from the start and end of a string. it will not remove spaces between characters. If you want to remove the spaces use str_replace

Share this post


Link to post
Share on other sites
[code]$keywords = preg_split('/\s*,\s*/', $postedList);[/code]

Share this post


Link to post
Share on other sites
You didn't put the trimmed keywords back into the array

[code]foreach($keywords as $index=>$keyword){
$keyword = trim($keyword); //remove spaces from each value in array
$keywords[$index] = $keyword;
}[/code]

Edit: effigy has the better solution.

Share this post


Link to post
Share on other sites
Actually, although the preg_split is better, you needed to reference $keyword:

[code]
foreach ($keywords as &$keyword) { ... }
[/code]

Share this post


Link to post
Share on other sites
thanks effigy for both your posts.
that solves my problem.
I guess I didn't grasp the concept as well as I had thought.

Share this post


Link to post
Share on other sites
Use the function array_map()  http://www.php.net/manual/en/function.array-map.php
[code]<?php $keywords = array_map(trim,$keywords); ?>[/code]

Nice and simple.

Ken

Share this post


Link to post
Share on other sites
kenrbnsn, I like that. I've never noticed that array function before.
karma++

Share this post


Link to post
Share on other sites
it should be noted that array_map() will only work for one level of an array.  check the comments for a deep_map() type of function that will map the function to all levels of an array.

Share this post


Link to post
Share on other sites
I didn't know it existed until about a month ago when it was mentioned as a reply to a reply I made to another question here.

Now, I seem to be using it all over. :)

Ken

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.