Welcome Guest, Not a member yet? Register   Sign In
Form Array and removing spaces?
#1

[eluser]ywftdg[/eluser]
I have a form on my website that allows users to enter keywords.
Typically in the form of something like: dog, cat , my pet, animal

What I want to do, is remove any spaces (during the form submission to the db) before/after the commas (which could be 1, 2, 3 spaces depending on how spastic the user is).

The items above would result in: dog,cat,my pet,animal
Notice it leaves the space in 'my pet'

Right now I am using this code below for the form field, but have tried, trim, ltrim, all sorts of things but nothing working. Any ideas?

Code:
<? $keywords = array ( 'name'=>'keywords' , 'id'=>'keywords' , 'value' => $this->validation->keywords, 'size' => '60', 'class' => 'formtextA' ) ?>
<?=form_input($keywords)?>
#2

[eluser]bretticus[/eluser]
Use preg_replace to match empty strings and commas and replace globally (see preg php functions.)

Or, explode (build an array) and split on commas. Iterate through your array and trim each member. implode (or join) your array to create a new filtered string.
#3

[eluser]mddd[/eluser]
I agree with bretticus.
If you are eventually going to store the keywords as seperate entries in a table, I would user explode and then trim.
If you want to store them together as a single string, I would use preg_replace to replace comma's surrounded by empty space by a single comma.
Code:
$output = explode(',', $input);
foreach($output as &$str)
   $str=trim($str);
// use output as an array

// or:

$output = trim(preg_replace('#\s*,+\s*#', ',', $input));
// use output as a string




Theme © iAndrew 2016 - Forum software by © MyBB