我正在创建一个论坛,用户可以在其中输入文本,并可以使用特定方法进行格式化。我已经能够使用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>
这里的问题是,我知道如何替换<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;
}
感谢您的帮助
试试这个代码。
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;
}