Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace spaces and newlines with a comma in php

Tags:

php

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.

like image 590
salty Avatar asked Jul 24 '13 15:07

salty


2 Answers

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));
like image 60
MDEV Avatar answered Oct 20 '22 04:10

MDEV


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.

like image 41
Jason McCreary Avatar answered Oct 20 '22 04:10

Jason McCreary