Spaceman Spaceman - 2 months ago 12
PHP Question

php convert text list into html list

I have a table column that contains a list of items separated by "br" tag(no new lines).

I fetch this data and convert br tags to new lines like as defined below.

$nlformat = str_replace("<br>","\n",$mem['mem_services']);


I'm also writing a file in this php script that will turn this list into an html list with "li" tags. This is easy, BUT if the list has two consecutive new lines "\n\n" I want to end the first list and create a second list like so...

<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>
<ul>
<li>item</li>
<li>item</li>
<li>item</li>
</ul>


I'm having an issue identifying 2 consecutive new lines in the following variable. Below is just one of many examples from other answered questions on this site. None of them work

$newul = preg_replace("/\r\n\r\n|\n\n|\r\r/", "</li></ul><ul><li>", $nlformat);


Does anyone know why. Maybe it has something to do with the $nlformat variable.

With the current example I get no change to $nlformat i.e.

item
item
item

item
item
item

Answer

My approach to this question is, I have a string that has \n char in between. I will first build an formatted array out of it and then build html out of it. So that you can use section of code that is related to your problem

Please try this way.

$nlFormat="item\nitem\nitem\n\nitem\nitem\nitem";
$tmp_arr1= explode("\n\n",$nlFormat);
$final_arr=array();
// now $tmp_arr1 has n number of sections;
foreach($tmp_arr1 as $section){
    $final_arr[]= explode("\n",$section);
}

//var_dump($final_arr);

now lets generate html

$html="";
foreach($final_arr as $section){
    $html.="<ul><li>";
    $html.=implode("</li><li>",$section);
    $html.="</li></ul>";
}
echo $html;

Hope this helps you

Comments