0

I received an input from a textarea in this format:

value0
value1
value2
value3

Now i want to explode this into an array, and implode back to string so that

INSERT INTO `table` (`valueField`, `myField`) VALUES
('value0','assignedValue'),
('value1','assignedValue'),
('value2','assignedValue'),
('value2','assignedValue')

Where assignedValue is fixed.

Here is what I did:

$myArray = explode(PHP_EOL, $_POST['input']);
foreach ($myArray as $key => $value) {
    $myArray[$key] = trim(preg_replace('/\s\s+/', ' ', $value));
}
$data = "('" . implode("','assignedValue'),'", $myArray) . "'";
$sql = "INSERT INTO `table` (`valueField`, `myField`) VALUES $data";
echo $sql;

As the result, which is wrong:

INSERT INTO `table` (`valueField`, `myField`) VALUES ('value0','assignedValue'),'value1','assignedValue'),'value2','assignedValue'),'value3'

Also if there is a better way to do this in regex please.

1 Answer 1

2

If you want to do it using implode you have to do:

$data = "('" . implode("','assignedValue'),('", $myArray) . "','assignedValue')";

A little nicer is:

foreach ($myArray as $key => $value) {
    $value = trim(preg_replace('/\s\s+/', ' ', $value));
    $myArray[$key] = '(\''. $value .'\',\'assingedValue\')';
}
$data = implode(',', $myArray);
Sign up to request clarification or add additional context in comments.

1 Comment

I added something about my question, but you may not answer it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.