Question

I have a single textarea input in my html form. Users will write in that textarea like this:

  • 5x Blue Flower
  • 2 Red Flower
  • 3* Yellow Flower
  • Purple Flower

So i need to get two arrays from this. One is a number and the other is the flower.

For now i got the numbers in array but i am struggling with getting only flowers in the second array. Also, where they don't put a number, there should be a default number 1.

$text_data = $_POST['tekst'];
$input = explode("\n", $text_data);
foreach($input as $line)
{
$number = preg_replace("/[^0-9]/", '', $line);
echo $number . '<br>';
echo $line;
}

Any help would be much appreciated.

Was it helpful?

Solution

Try

foreach($input as $line){
 preg_match("/\d+/", $line, $matches);
 $line = preg_replace("/\d+/",'' ,$line);
 $number = (isset($matches[0]))?$matches[0]:1;
 if(strlen($line)>0){
   echo $number."-->".$line."\n";
 }
}

See demo here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top