从php中的字符串格式化HTML列表

时间:2015-06-26 08:31:05

标签: php substring

我正在创建一个论坛,用户可以使用某种方法输入可以格式化的文本。我已经能够使用substring()完成大部分字符串工作,但是我在订购列表和无序列表上遇到了问题。

我以无序为例。

用户输入将是:

Example of text and here is my UL:
* Element 1
* Element 2
* Element 3
* Element 4
* Element 5

Thank you. Another one:
* Another 1
* Another 2

它会像这样进入数据库然后我想在php中解决这个问题以获得以下输出:

Example of text and here is my UL:
<ul>
    <li>Element 1</li>
    <li>Element 2</li> 
    <li>Element 3</li> 
    <li>Element 4</li> 
    <li>Element 5</li> 
<ul>

Thank you. Another one:
<ul>
    <li>Another 1</li>
    <li>Another 2</li> 
<ul>

这里的问题是我知道如何更换&#34; *&#34;对于<li>,但我无法弄清楚如何找到前5个,然后找到另外2个,这样他们就可以在它们周围找到它们的ul标签<ul></ul>

我在我的功能开始时使用了bl2br()所以cariage都是

在这里,我的功能的一部分削减了一点,以帮助:

function String_ToOutput($String_Output){

    //Replace Cariage with HTML Code
    $Temp_String = nl2br($String_Output);

    //List Code
    while(($pos = strpos($Temp_String, "\n*")) !== false){
        $Temp_String = substr($Temp_String, 0, $pos) . "<ul><li>" . substr($Temp_String, $pos + 3);
        $pos = strpos($Temp_String, "\n", $pos);
        while((substr($Temp_String, $pos+1, 1)) == "*"){
                $Next = strpos($Temp_String, "\n", $pos);
                $Temp_String = substr($Temp_String, 0, $pos) . "<li>" . substr($Temp_String, $pos + 2);
                $pos = $Next;
        }
    }


    return $Temp_String;
}

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

您是否可以使用Markdown语法执行此操作?这样你就不必重新发明轮子了。

答案 1 :(得分:1)

Try this code.

function String_ToOutput($String_Output){

    //Replace Cariage with HTML Code
    $Temp_String = nl2br($String_Output);

    $lines=explode("\n",$Temp_String);

    $start_list=false;
    foreach($lines as &$line){ 
        if(strpos($line,'*')!==False){
            if(!$start_list)
                $line="<ul> ".$line;
            $line=str_replace('*',"<li>",$line)."</li>";
            $start_list=true;
        }
        else{

            if($start_list){
            $start_list=false;
            $line="</ul> ". $line;
            }
        }
        //echo $line;
    }
    $sring=implode("\n",$lines);
    return $sring;
}