Page 1 of 1

Formatting Text from $_GET

Posted: Wed Aug 19, 2009 6:34 pm
by ASherbuck
Hello,
I'm coming over from VB and I'm trying a few things to get my feet wet in PHP and I've ran into my first problem.

My goal is to take the text from a textarea and format each row into a single line separated by commas.
For example:
If the textarea contains
"1
2
3
4"
I would like to output to be "1,2,3,4"

The following is my code:

Code: Select all

<?php
echo "<Form action='index.php' method='get'>";
echo "<textarea name='Box' rows='10' cols='25'></textarea>";
echo "<input type='submit'/>";
echo "</form>";
 
$StrVar = $_GET['Box'];
 
$StrVar = str_replace(" ", ",", $StrVar);
 
echo $StrVar;
 
?>
My output is "1 2 3 4"
I tried replacing "%0D%0A" instead of " " as that is what appears in the browser. However, that did not work either. I do not possess the knowledge/tools yet to figure out why this isn't working, my hunch is that the php stores a different value for that space and I don't know what it is. Or perhaps the $StrVar is not being defined as a string so str_replace does not work? Any help with this would be greatly appreciated.

Re: Formatting Text from $_GET

Posted: Wed Aug 19, 2009 6:49 pm
by aceconcepts
Welcome to PHP :D

You could use something like this:

Code: Select all

 
echo "<Form action='index.php' method='get'>";
echo "<textarea name='Box' rows='10' cols='25'></textarea>";
echo "<input type='submit'/>";
echo "</form>";
 
$StrVar = trim($_GET['Box']);
 
$formatted_var = str_replace("\n", ", ", $StrVar);
 
echo $formatted_var;
 

Re: Formatting Text from $_GET

Posted: Wed Aug 19, 2009 7:00 pm
by ASherbuck
Thanks for the reply aceconcepts,
That certainly works to get the comma between the rows but an extra space is being put in right before the comma.

Does the line break have anything to do with that?

Re: Formatting Text from $_GET

Posted: Wed Aug 19, 2009 7:32 pm
by aceconcepts
In that case lets try an alternative approach:

Code: Select all

 
$StrVar = trim($_GET['Box']);
 
//split the string into an array
$formatted_var = explode("\n", $StrVar);
        
//loop through array
foreach($formatted_var as $key=>$value)
{
//remove unwanted whitespace
$formatted_var[$key] = trim($value);
}
        
//create new string
$new_string = implode(", ", $formatted_var);
        
echo $new_string;
 

Re: Formatting Text from $_GET

Posted: Wed Aug 19, 2009 9:16 pm
by Ollie Saunders
aceconcepts' solution more concisely:

Code: Select all

$linesAsCommas = implode(', ', array_map('trim', explode(PHP_EOL, $_GET['Box'])));

Re: Formatting Text from $_GET

Posted: Wed Aug 19, 2009 10:05 pm
by aceconcepts
Very nice Ollie :D

Re: Formatting Text from $_GET

Posted: Thu Aug 20, 2009 11:23 am
by ASherbuck
Very nice,

Thank you for your help.