Replace Space by Comma

Asked

Viewed 425 times

-2

$var = 123 456 789;

I need the value of this variable to stay:

$var = 123,456,789;

Or add a comma after the number:

$var = 123, 456, 789;

I tried so:

str_replace($var," ","")
  • 1

    Do the opposite: str_replace(" ",",", $var)

3 answers

1

You are almost there. The arguments of the function str_replace 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 http://php.net/manual/en/

1

One way not to forget the order is:

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

translating to PHP

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

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

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

You have to put in quotes 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 the ideone

0

To use STR_REPLACE you need to transform the contents of the variable into a string so you must quote the numbers. Then you go on to replace the spaces with the commas in str_replace, but then you need to pass the received value of replace to a variable that will store the new value. And then you can even split up then explode.

$var = '123 456 789';
$texto = str_replace( ' ', ', ', $var );
echo $texto;
$array = explode( ',', $texto );
var_dump($array);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.