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

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

$variable should become:

one<br>
two<br>
three
Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
James
  • 42,081
  • 53
  • 136
  • 161

5 Answers5

13

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);
Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
8
$variable = str_replace(", ","<br>\n",$variable);

Should do the trick.

Jimmie Clark
  • 1,878
  • 13
  • 25
5
$variable = explode(', ',$variable);
$variable = implode("<br/>\n",$variable);

You can then just echo $variable

neopickaze
  • 981
  • 8
  • 14
3

You can do:

$variable = str_replace(', ',"<br>\n",$variable);
codaddict
  • 445,704
  • 82
  • 492
  • 529
3
$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
  • 31
  • 1