Click to See Complete Forum and Search --> : [RESOLVED] Splitting textarea input into array by newline...


KingCobra220
06-15-2007, 11:14 AM
Well, the title says it all. First, I got the input from the textarea to a variable. Next, I want to split that string into an array, dividing it by each newline. Depending on the client's OS, newline can be \n, \r, or \r\n.

Here is what I tried:

$array = split('[\n,\r,\r\n]', $textarea_input);

I just started teaching myself php yesterday and I was wondering if this would work to print the array to the screen:

<?
for($x=0; $x<sizeof($array); $x++){
echo $array[$x];
?>
<br>
<? } ?>

NogDog
06-15-2007, 01:08 PM
$array = preg_split('/(\r?\n)+/', $textarea_input);

This is saying, 'split on one or more consecutive instances of "\r" or "\r\n",'

KingCobra220
06-15-2007, 01:34 PM
If what you told me is correct, my for loop is incorrect. I tried the code. I didn't get any errors, which is good, but nothing was printed to the screen.

NogDog
06-15-2007, 01:42 PM
This worked OK for me:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang='en'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'>
<META name="description" content="">
<meta name="keywords" content="">
<title>Untitled</title>
<!-- link rel='stylesheet' href='/include/style.css' type='text/css' -->
<style type="text/css">
<!--
-->
</style>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<legend>Newline Test</legend>
<textarea name="test" cols="60" rows="10"></textarea><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<?php
if(count($_POST))
{
echo "<p>You entered:</p>\n<ul>\n";
$array = preg_split('/(\r?\n)+/', $_POST['test']);
foreach($array as $line)
{
echo "<li>$line</li>\n";
}
echo "</ul>\n";
}
?>
</body>
</html>