Replace space with Comma

-2
$var = 123 456 789;

I need the value of this variable to be:

$var = 123,456,789;

Or add a comma after the number:

$var = 123, 456, 789;

I tried this way:

str_replace($var," ","")
    
asked by anonymous 11.10.2018 / 03:45

3 answers

1

You're almost there. The arguments of the str_replace function that are in the wrong order.

According to the PHP documentation you can consult here , you need to do the following:

$resultado = str_replace(' ', ',', $var);  // resultado: 123,456,789;
// ou
$resultado = str_replace(' ',', ', $var);  // resultado: 123, 456, 789;

You can always refer to the PHP reference that indicates related functions and other important content in link

    
11.10.2018 / 04:15
0

To use STR_REPLACE you need to transform the contents of the variable into a string, so you must leave the numbers in quotation marks. Then you pass to replace the spaces with the commas in str_replace, but then you need to pass the value received from replace to a variable that will store the new value. And then you can even detach with explode.

$var = '123 456 789';
$texto = str_replace( ' ', ', ', $var );
echo $texto;
$array = explode( ',', $texto );
var_dump($array);
    
11.10.2018 / 04:07
0

One way to not forget the order is:

substituir('este', 'por este', 'neste');

translating to PHP

str_replace(' ', ',', $var)
  

$ var = 123 456 789; is not number nor string, so it will generate an error in PHP

 PHP Parse error:  syntax error, unexpected '456' (T_LNUMBER) in source_file
  

You must enclose it in quotation marks to be treated as a string

$var = "123 456 789";

//errado não vai imprimir nada
echo str_replace($var," ","").PHP_EOL;

//substitui espaço por virgula
echo str_replace(" ",",",$var).PHP_EOL;

//substitui espaço por virgula mais espaço
echo str_replace(" ",", ",$var).PHP_EOL;

running on ideone

    
11.10.2018 / 04:18