维基百科风格列表编辑


Wikipedia style list editing

谁能建议如何使用PHP创建项目符号列表的最佳方法,就像维基百科在编辑页面时所做的那样(实际上是StackOverflow)?

用户将以保存在数据库中的表单输入以下内容...

text text text
My bullet list:
* bullet 1
* bullet 2
* bullet 3
Some more text here.

在页面上调用时,将字符串转换为...

text,text,text
My bullet list:
<ul>
<li>List point one</li>
<li>List point two</li>
</ul>
Some more text here.

我正在玩str_replace,显然可以轻松地用 html 标签替换星星,但我如何添加结束标签等?

您还可以使用带有少量正则表达式的字符串操作来完成此操作。这将替换所有以 * 开头的行,使其成为无序列表。

$some_string = ""; // your input string goes here
$string_array = explode( "'r'n", $some_string ); //here we create an array from the string, broken up by new lines
for($i = 0; $i < count( $string_array ); $i ++) {
    if (preg_match( '/^'*/', $string_array [$i] ) == 1 && preg_match( '/^'*/', $string_array [$i-1] ) == 0 && strpos( $string_array [$i - 1], '<ul>' ) === false && strpos( $string_array [$i - 1], '<li>' ) === false)
        $string_array [$i] = "<ul>'n<li>" . preg_replace( '/^'*'s/', '', $string_array [$i] ) . '</li>';
    elseif (preg_match( '/^'*/', $string_array [$i] ) == 1)
        $string_array [$i] = '<li>' . preg_replace( '/^'*'s/', '', $string_array [$i] ) . '</li>';
    if (preg_match( '/^'*/', $string_array [$i+1] ) == 0 && strpos( $string_array [$i], '</li>' ) !== false)
        $string_array [$i] .= "'n</ul>";
}
$result = implode( "'r'n", $string_array ); //here we reconstruct the array
echo $result;

这是一个粗略的例子,但它应该让你了解你可以用这样的字符串做什么

我建议使用正则表达式,

例如

$input = "* this is a list item"

您可以使用

preg_replace("/'*'s([a-z].*)/", "<li> $1 <li>", $input);

要得到

<li> this is a list item </li>

如果您对如何使用preg_replace感到好奇http://php.net/manual/en/function.preg-replace.php