php - Preserve line break in string inside array
I am trying to output this string returned to me via API
but when I print it using this
<?php echo $m["page_features"]; ?>
it is printed like folloing (single line)
Bunkhouse Front Bedroom Kitchen Island Loft Outdoor Kitchen 4 Slide-Outs
But I want it like
- Bunkhouse
- Front Bedroom
- Kitchen Island
- Loft
- Outdoor Kitchen
- 4 Slide-Outs
How can I achieve the result as desired output, please help
Answer
Solution:
Use nl2br for regular line breaks
<?php echo nl2br($m["page_features"]); ?>
for a UL list:
<?php
$features = explode("\n",$m["page_features"]);
if (count($features)>0){
echo"<ul>";
foreach($features as $f) echo"<li>$f</li>";
echo "</ul>";
}
?>
Answer
Solution:
Solution is use php explode function and forloop (any loop) to loop for each value ..
It would be really helpful if you provide complete code !
So taking 2 assumtions first the data recived has br tag and second it has too many whitespaces ....
If i assume the tag used was
then try this one
<?php
$str = "Bunk house <br> Front Bedroom <br> kitchen <br> island <br> loft <br> etc";
$array = array_filter(explode("<br>",$str));
foreach ($array as $value){
echo "<li>".$value."</li><br>";
}
?>
If I assume that there are too many whitespaces inside the string then code becomes
<?php
$str = "Bunk house Front Bedroom kitchen island loft etc";
$array = array_filter(explode(" ",$str));
foreach ($array as $value){
echo "<li>".$value."</li><br>";
}
?>
Source