2014-10-11 71 views
0

我一直在使用PHP自己製作的論壇,它驚人地來臨,但我試圖找出是否有辦法檢查匹配的BBCode標籤?我有我自己的陣列設置替換<b>[b]等,但我希望能夠確保標籤將關閉在某個點[/b]而不是繼續運行的職位和其餘的頁。PHP檢查用戶匹配標籤在用戶提交內容

例如:[b]This is text將顯示爲[b]This is text,並[b]This is text[/b]將在頁面上返回的<b>This is text</b>

有沒有辦法做到這一點,還是有辦法在PHP/HTML的任何打開的「逃離」標籤? IE瀏覽器;如果該帖子中沒有[/b],則自動在其末尾添加一個</b>

+0

http://snipplr.com/view/3618/ http://htmlpurifier.org/ http://stackoverflow.com/questions/3810230/php-how-to-close-open-html- tag-in-a-string – honzahommer 2014-10-11 03:38:50

回答

0

這是您的要求很簡單的bbcode解析器做你的工作:

function bbcode($data) 
{ 
    $input = array(
     '/\[b\](.*?)\[\/b\]/is', 
     '/\[b\](.*?)$/', 
    ); 
    $output = array(
     '<b>$1</b>', 
     '<b>$1</b>', 
    ); 
    return preg_replace ($input, $output, $data);; 
} 

一些例子:

bbcode('[b]text[/]'); 
//returns <b>text</b> 

bbcode('[b]text'); 
//returns <b>text</b> 

參見示例運行here

+0

這工作得很好,謝謝! – TheElm 2014-10-11 04:45:57

+0

只是一個評論,其他標籤你需要做同樣的正則表達式。 – rogelio 2014-10-11 04:52:11

-1

所以在這裏要分析出來的HTML標籤UBB標籤,這裏有一個小的功能,我發現在網上可以很容易地

<?php 

/* Simple PHP BBCode Parser function */ 

//BBCode Parser function 

function showBBcodes($text) { 

// BBcode array 
$find = array(
'~\[b\](.*?)\[/b\]~s', 
'~\[i\](.*?)\[/i\]~s', 
'~\[u\](.*?)\[/u\]~s', 
'~\[quote\](.*?)\[/quote\]~s', 
'~\[size=(.*?)\](.*?)\[/size\]~s', 
'~\[color=(.*?)\](.*?)\[/color\]~s', 
'~\[url\]((?:ftp|https?)://.*?)\[/url\]~s', 
'~\[img\](https?://.*?\.(?:jpg|jpeg|gif|png|bmp))\[/img\]~s' 
); 

// HTML tags to replace BBcode 
$replace = array(
'<b>$1</b>', 
'<i>$1</i>', 
'<span style="text-decoration:underline;">$1</span>', 
'<pre>$1</'.'pre>', 
'<span style="font-size:$1px;">$2</span>', 
'<span style="color:$1;">$2</span>', 
'<a href="$1">$1</a>', 
'<img src="$1" alt="" />' 
); 

// Replacing the BBcodes with corresponding HTML tags 
return preg_replace($find,$replace,$text); 
} 

// How to use the above function: 

$bbtext = "This is [b]bold[/b] and this is [u]underlined[/u] and this is in [i]italics[/i] with a [color=red] red color[/color]"; 
$htmltext = showBBcodes($bbtext); 
echo $htmltext; 

?> 
+0

這不是@TheElm正在尋找的答案。他說,如果bbcode未關閉,請在末尾添加相應的結束標記 – rogelio 2014-10-11 03:44:34

+0

從中獲得的正則表達式非常有用,以及rogello的答案是讓它在關閉後關閉標記。感謝你的回答! – TheElm 2014-10-11 04:46:42