0

Im really stumped on trying to format user input. I have an input box where users enter data separated by commas. Then I explode it:

$data = $_POST['data'];
$words = explode(',', $data);

then I'm analyzing each word. Everything works perfectly when you enter the data correctly. However, if someone typed in "bird, car, train,," or any other similar error it makes my results incorrect.

I'm drawing a blank on how I could build a function to format the user input to make sure there aren't errors like extra commas or other intruding characters.

Any ideas??

4
Contributors
10
Replies
11
Views
5 Years
Discussion Span
Last Post by diafol
Featured Replies
0

The input represents terms that are analyzed with a different part of the program. I thought of a function like that but it wouldn't be very efficient to make it only remove double commas. And it can't remove all spaces because some of the words to be analyzed are phrases. such as "rowing, street racing, climbing". Thanks for ur input tho

0

Then it would be more like this I guess.

$data = $_POST['data'];
$newwords = array ();
$words = explode(',', $data);
foreach ($words as $word)
{
  if (!empty(trim($word)))
  {
    $newwords[] = $word;
  }
}

Edited by pritaeas: n/a

0

If it is as simple as finding extra commas and/or whitespace then (using prieas example with one extra line and a new variable):

$data = $_POST['data'];
$newdata = str_replace(",,", ",", trim($data));
$words = explode(',', $newdata);
foreach ($words as $word)
{
  if (!empty(trim($word)))
  {
    $newwords[] = $word;
  }
}
0

@purplepixie: the loop already takes care of the extra comma's. The str_replace does not remove say ,,,,

0

Thanks for the ideas.. Pritaeas, I used your example but for some reason it didn't integrate correctly with my code, I ended up getting this to work tho:

$arr = explode(',', $data);
$inc = 0;
	foreach($arr as $trimmed)
	{
		$symp[$inc] = trim($trimmed);
		$inc++;
	}
	$symp_user_view = implode(', ', $symp);

which is pretty much the same concept...
thanks for the help!

0

how's this? it should save you looping

echo trim(preg_replace("/(,)(\s*,\s*)*/",'${1}',$input));

Pritaeas will know better than me, but I think it'll strip extra commas and whitespace, leaving just a single comma.
You could change it to convert ; to , as well and so on.

Edited by diafol: n/a

0

thanks ardav, i tried your method, however it didn't work with my script, probly cus i have so much stuff going on at once.. anyways i found this method which i think is working the best for me...

$arr = $_POST['input'];
$arr = preg_replace("/[^a-zA-Z 0-9]+/", "", $arr);
$arr = array_filter($arr); 
$inc = 0;

foreach($arr as $trimmed)
{
	$symp[$inc] = trim($trimmed);
	$inc++;
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.