How to split text from a jquery post into an array
I have a textarea that I want the user to be able to enter va开发者_如何学Criables into (one variable per line). When they click submit I then send what they've entered with a jQuery post to a php script like so:
$('#submit').click(function() {
variables = $('#variables').val();
$.post('script.php', { "variables": variables }, function(data) {
}, 'json');
});
I recieve the string ok in the script easily with:
$variables = $_POST['variables'];
but how would I split this string of variables into an array? I have tried:
$variableList = explode("\r\n", $variables);
preg_replace("\r\n", '<br />', $variables);
str_replace("\r\n", '<br />', $variables);
Can anyone help please?
Although you didn't specify your SO, I believe the problem is because you're not splitting the right thing:
On a Mac, this is called the Carriage Return, or CR, character. On a Windows editor, the enter key inserts a Carriage Return – Line Feed, (CR-LF), character, and on a Linux machine, it’s a Line Feed, (LF), character.
source: http://www.paulmc.org/whatithink/2007/03/25/cr-vs-lf-vs-crlf/
Instead of:
$variableList = explode("\r\n", $variables);
Try:
$variableList = explode("\n", $variables);
See these: http://forum.jquery.com/topic/jquery-split-form-field-into-array
As I'm unsure whether the line break you get from Windows users will be \r\n
or if everything will be normalized to \n
, I suggest to try regular expressions:
$list = array_map('trim', preg_split("/$/m", $variables));
or if it gets normalized, as suggested in my comment:
$list = explode("\n", $variables);
精彩评论