更改分隔符#
到/
。並將「/[/b\]
」更改爲「\[\/b\]
」。因爲你需要它作爲文字字符,你需要轉義「/」。
也許「array()
」應該使用括號:「array[]
」。
注:我借了答案從這裏:Convert BBcode to HTML using JavaScript/jQuery
編輯:我忘了,「/」是不是元字符,所以我相應的編輯答案。
更新:我無法使它與函數一起工作,但是這個工作。查看評論。 (我在上面鏈接的問題中使用了接受的答案進行測試,也可以這樣做。)請注意,這是JavaScript。你的問題有你的PHP代碼。 (我不能幫你的PHP代碼至少一段時間。)
$str = 'this is a [b]bolded[/b], [title=xyz xyz]Title of something[/title]';
//doesn't work (PHP function)
//$str = htmlentities($str);
//notes: lose the single quotes
//lose the text "array" and use brackets
//don't know what "ig" means but doesn't work without them
$format_search = [
/\[b\](.*?)\[\/b\]/ig,
/\[title=(.*?)\](.*?)\[\/title\]/ig
];
$format_replace = [
'<strong>$1</strong>',
'<div class="box_header" id="$1"><center>$2</center></div>'
];
// Perform the actual conversion
for (var i =0;i<$format_search.length;i++) {
$str = $str.replace($format_search[i], $format_replace[i]);
}
//place the formatted string somewhere
document.getElementById('output_area').innerHTML=$str;
UPDATE2:現在用PHP ......(對不起,你必須格式化$replacements
根據自己的喜好我只是添加了一些標籤和文字來展示變化。)如果「標題」仍然存在問題,請查看您嘗試設置格式的文本類型。我在?
上標題「=」是可選的,所以它應該能正常工作,例如:「[標題=有一個或多個單詞的標識]標題帶有標識[/標題]」和「[標題]標題沒有標識[/標題] 。不知道想如果id
屬性允許有空間,我不這樣想:http://reference.sitepoint.com/html/core-attributes/id
$str = '[title=title id]Title text[/title] No style, [b]Bold[/b], [i]emphasis[/i], no style.';
//try without this if there's trouble
$str = htmlentities($str);
//"#" works as delimiter in PHP (not sure abut JS) so no need to escape the "/" with a "\"
$patterns = array();
$patterns = array(
'#\[b\](.*?)\[/b\]#',
'#\[i\](.*?)\[/i\]#', //delete this row if you don't neet emphasis style
'#\[title=?(.*?)\](.*?)\[/title\]#'
);
$replacements = array();
$replacements = array(
'<strong>$1</strong>',
'<em>$1</em>', // delete this row if you don't need emphasis style
'<h1 id="$1">$2</h1>'
);
//perform the conversion
$str = preg_replace($patterns, $replacements, $str);
echo $str;
我編輯的代碼,不使用#和所做的任何/成爲\/ 但[標題=] [/標題]仍然無法工作? – Rynosapien 2012-04-09 19:38:39
@Rynosapien看到我的更新的答案。我能夠使它工作得很好。 – 2012-04-09 20:31:03
@Rynosapien正則表達式是否有效取決於要格式化的字符串的結構。[title = xxx yyy] zzz yyy [/ title]現在應該接受多個詞作爲標題ID和標題文本。 – 2012-04-09 20:37:28