2014-12-02 67 views
0

任何人都可以提出如何使用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標籤替換一個明星,但我如何添加結束標籤等?

+0

http://daringfireball.net/projects/markdown/ – mudasobwa 2014-12-02 15:03:13

+0

那在Perl,而不是自由。 – vaso123 2014-12-02 15:06:10

+0

儘管您可能需要使用其他語言編寫自己的實現,但我確定它說:「Markdown是免費軟件,可以在BSD風格的開源許可下獲得。」 – 2014-12-02 15:10:46

回答

0

你也可以使用字符串處理和一點正則表達式來實現這一點。這將替換所有以*開頭的行成爲無序列表。

$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; 

這是一個粗略的例子,但它應該給你的,你可以用繩子做什麼樣的一個想法,這個