1

I've been trying to sort this out for weeks, but can't get anywhere. My issue is that I have an array in javascript but the individual phrases in the array also have commas in them. I am passing the array as a variable to php using POST and php is exploding the array into variables, but is also separating parts of the array members that have a comma.

Step 1: Array in javascript

wrongOnes = ("blah blah blah", "bing, boing, bing");

Step 2: read by php

$myArray = explode(',', $_POST["wrongOnes"]);

Step 3: this is then made into a message to be posted

foreach($myArray as $my_Array){
$message .= "\r\n".$my_Array;  
}

You can see that the problem is exploding and separating at the commas makes extra members of $myArray.

I feel that the answer should be easy, but my current level of php is weak. Can anyone help?

Cheers

Charco.

charco
  • 71
  • 6

2 Answers2

0

Here you go, as long as they are quoted like you example.

$str = '"blah blah blah", "bing, boing, bing"';

preg_match_all('/"(.*?)"/', $str, $match);

print_r($match[1]);

Output

 Array
(
    [0] => blah blah blah
    [1] => bing, boing, bing
)

You can try it here

http://sandbox.onlinephpfunctions.com/code/b12ba98b423d7e1dda792f3bd51e11cdb3fa1c16

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • Amazingly quick reply, thanks. You couldn't explain how it works, could you please? – charco Nov 08 '17 at 10:34
  • its a Regular expression that captures everything between the `"` quotes, Regular expressions are for pattern matching in strings. – ArtisticPhoenix Nov 08 '17 at 10:47
  • I am not getting the required output from my array: I am using preg_match_all('/"(.*?)"/', $_POST["wrongOnes"], $match); and then attempting to send this as part of my message by email: $message .= " The following questions were answered incorrectly: "; $message .= $match[1]; and the resultant email just substitues the $match[1] by the word "Array" – charco Nov 08 '17 at 11:54
0

1) JSON encode your array in javascript before sending it

by using the stringify method of JavaScripts JSON Object

jsonString = JSON.stringify(wrongOnes)

and

2) Decode the JSON in PHP using the json_decode function

$myArray=json_decode($_POST['jsonString']);

to get your original array back.

References:

PHP json_decode
JavaScript JSON.stringify

If you happen to miss the json module in your installation check this StackOverflow post:
PHP Fatal error: Call to undefined function json_decode()

Minzkraut
  • 2,149
  • 25
  • 31