tags:

views:

85

answers:

5
$variable = 'one, two, three';

How can I replace the commas between words with <br>?

$variable should become:

one<br>
two<br>
three
+11  A: 

Either use str_replace:

$variable = str_replace(", ", "<br>", $variable);

or, if you want to do other things with the elements in between, explode() and implode():

$variable_exploded = explode(", ", $variable);
$variable_imploded = implode("<br>", $variable_exploded);
Pekka
+9  A: 
$variable = str_replace(", ","<br>\n",$variable);

Should do the trick.

Jimmie Clark
+5  A: 
$variable = explode(', ',$variable);
$variable = implode("<br/>\n",$variable);

You can then just echo $variable

D Roddis
this is pretty expensive..
Frederico
+3  A: 

You can do:

$variable = str_replace(', ',"<br>\n",$variable);
codaddict
+3  A: 
$variable = preg_replace('/\s*,\s*/', "<br>\n", $variable);

This takes you into regex land but this will handle cases of random spacing between commas, e.g.

$variable = 'one,two, three';

or

$variable = 'one , two, three';
CT Sung