我理解标题含糊不清,但我需要帮助解决这个问题。我似乎无法绕过它。
基本上,我有一个textarea,用户可以在其中插入字符串/文本:
Blah blah blah blah blah this is random text whatever it could be blah blah
* Un-ordered list item
* Un-ordered list item
Blah blah blah and here is some more random text because blah blah blah
* Un-ordered list item
* Un-ordered list item
如您所见,用户可以通过添加PHP脚本刚刚修改的*
字符来创建列表,以生成相应的列表标记。
到目前为止我所拥有的是:
$text = array();
$c = 0;
foreach($lines as $line) {
if(strpos($line, "*") !== FALSE) {
if($c == 0) {
$text[] = "<ul>";
}
$text[] = "<li>" . trim(str_replace(array("*", "\n"), '', $line)) . "</li>";
$c++;
} else {
$c = 0;
$text[] = $line;
}
}
哪会返回这样的内容:
Array
(
[0] => Blah blah blah blah blah this is random text whatever it could be blah blah
[1] =>
[2] => <ul>
[3] => <li>Un-ordered list item</li>
[4] => <li>Un-ordered list item</li>
[5] =>
[6] => Blah blah blah and here is some more random text because blah blah blah
[7] =>
[8] => <ul>
[9] => <li>Un-ordered list item</li>
[10] => <li>Un-ordered list item</li>
)
我需要的是能够在列表完成后关闭<ul>
标记。正如您所看到的,用户可以根据需要添加任意数量的列表,因此代码块需要具有灵活性以适应这种情况。
以下是其中的一个示例:Example
答案 0 :(得分:1)
您需要添加一个标记,以便记住已启动无序列表,以及当您不再使列表添加到列表中时。像这样:
$text = array();
$c = 0;
$imalist = false;
foreach($lines as $line) {
if(strpos($line, "*") !== FALSE) {
if($c == 0) {
$text[] = "<ul>";
}
$text[] = "<li>" . trim(str_replace(array("*", "\n"), '', $line)) . "</li>";
$c++;
} else {
if ($c>0){
$text[] = "</ul>";
}
$c = 0;
$text[] = $line;
}
}
if ($c>0){
$text[] = "</ul>";
}
编辑:在循环后添加关闭,以防最后一行是列表项。
答案 1 :(得分:1)
这会有用吗?它添加了一个以前找到的任何列表项。
<?php
$text = array();
$c = 0;
$close=0;
foreach($lines as $line) {
if(strpos($line, "*") !== FALSE) {
if($c == 0) {
$text[] = "<ul>";
}
$text[] = "<li>" . trim(str_replace(array("*", "\n"), '', $line)) . "</li>";
$c++;
} else {
if($c>0){
$text[] = "</ul>";
}
$c = 0;
$text[] = $line;
}
}
?>
答案 2 :(得分:0)
只是设置一个标志。
$s = "Blah blah blah blah blah this is random text whatever it could be blah blah
* Un-ordered list item
* Un-ordered list item
Blah blah blah and here is some more random text because blah blah blah
* Un-ordered list item
* Un-ordered list item
";
$lines = explode("\n", $s);
$text = array();
$c = 0;
$flag=false; //set flag
foreach($lines as $line) {
if(strpos($line, "*") !== FALSE) {
$flag=true;
if($c == 0) {
$text[] = "<ul>";
}
$text[] = "<li>" . trim(str_replace(array("*", "\n"), '', $line)) . "</li>";
$c++;
} else {
if($flag==true){
$text[count($text)-1]=$text[count($text)-1]."</ul>";
$flag=false;
}
$c = 0;
$text[] = $line;
}
}
if($flag==true) $text[count($text)-1]=$text[count($text)-1]."</ul>";
print_r($text);