I am new to PHP
and while working on a project I face a problem. I have the following string Mango, Orange, Banana
Now I tried using str_replace(',', '<br/>',$string)
to replace the coma with the html tag <br>
but I get this result Mango<br/> Orange<br/> Banana
instead of
Mango
Orange
Banana
How can I solve this problem please?
The solution depends on where are you going to display the results.
In HTML page: then you should use the appropriate HTML markup around <br>
tags. This will tell browser to apply the default styles to your text (margins, line-breaks, etc).
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php echo str_replace(',', '<br>', 'Mango, Orange, Banana'); ?>
</body>
</html>
Anywhere else: then you should use the line break symbol. Different systems uses different symbols for line-break, but hopefully PHP has the pre-defined constant PHP_EOL
, that contains the line-break symbol.
<?php
echo str_replace(',', PHP_EOL, 'Mango, Orange, Banana');
?>
Seems like the str_replace works just fine, but the problem seems to be displaying html properly.
I tested using the following code, and it worked just fine.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$data = 'Mango, Orange, Banana';
$data = str_replace(',', '<br/>', $data);
echo $data;
?>
</body>
</html>
Remember to put the content inside html -> body tags