djoo
djoo

Reputation: 695

PHP : Best way to create array from textarea of variables

I have a textarea where users can put variables like this :

VARIABLE=foo
RANDOM=iloveit
GREAT=amazing

I need to transform this in an array of parameters.

So i did this function (who works) :

public static function cleanWebhookTextarea($textareaLines){

        $textareaLines = preg_split('/(;|,|\r\n,|\r,|\n)/', $textareaLines);
        $params = array();

        foreach ($textareaLines as $line){
            $line = preg_split('/(=)/', $line);
            $params[$line[0]] = $line[1];   
        }

        return $params;

    }

This return me what i want, so :

array:3 [▼
  "VARIABLE" => "foo"
  "RANDOM" => "iloveit"
  "GREAT" => "amazin"
]

But i wondering if there is a quickest way to do what i want ?

Thanks

Upvotes: 0

Views: 47

Answers (1)

Andrii  Filenko
Andrii Filenko

Reputation: 984

I guess you can do it in one line with function like str_replace and parse_str

parse_str(str_replace(PHP_EOL, '&', $data), $result);

Here is a working example.

Upvotes: 2

Related Questions