I searched but couldn't find anything that helped
So, I have a bunch of data I need to basically just put commas between, the data all comes from records so it comes in like:
13
566
888
958
898
and I need to output it like:
13,566,888,958,898
even better if I can move any 2 digits one over like:
566,13,888,958,989
I know it should be pretty simple, so basically I just made a form, pass it with GET and then read the variable from the url, then I'm trying to use str_replace(" ",",",$outtext) to get replace the spaces with commas so I can echo it out and just copypasta it in real quick, problem is, I think the data comes in with a new line and I don't know how to replace that, I've tried "\n" and "%0D%0A" but it doesn't replace it, it just gives it right back to me with the spaces.
Anyway, here's the code I'm using, maybe someone can tell me the simple thing that I'm missing,
<?php
if (isset($_GET['intext'])) {
$outtext=$_GET['intext'];
$newout=str_replace(" ", ",", $outtext);
echo $newout;
//testing
//echo(str_replace(" ",",","$outtext"));
}
?>
and the html
<form name="indata" id="indata" method="get" action="index.php">
<textarea id="intext" name="intext"></textarea>
<input type="submit" id="submit" name="submit">
</form>
I also thought about tossing it into an array and imploding it, but it's been a while and I forget how to do that.
The newline could still be registering if you've got the "\r\n" version of a newline - you're removing "\n" and leaving "\r" behind.
$str = preg_replace('/\s+/',',',str_replace(array("\r\n","\r","\n"),' ',trim($str)));
Cleaner (more legible) version:
$str = preg_replace('#\s+#',',',trim($str));
As you said, using an array then imploding is a good approach:
$input = trim($_GET['intext']);
$numbers = preg_split('/\s+/', $input);
echo implode(',', $numbers);
This trims the input of any padding, splits into an array based on whitespace, then implodes the array with commas.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With