PHP Preg_Replace REGEX BB-Code


PHP Preg_Replace REGEX BB-Code

所以我在PHP中创建了这个函数,以所需的形式输出文本。这是一个简单的BB代码系统。我已经从中剪掉了其他 BB 代码以使其更短(大约剪掉了 15 个)

我的问题是最后一个 [title=blue]Test[/title](测试数据)不起作用。它输出完全相同。我已经尝试了 4-5 个不同版本的 REGEX 代码,但没有任何改变。

有谁知道我哪里出了问题或如何解决它?

function bbcode_format($str){
$str = htmlentities($str);
$format_search =  array(
'#'[b'](.*?)'[/b']#is',
'#'[title=(.*?)'](.*?)'[/title']#i'
);
$format_replace = array(
'<strong>$1</strong>',
'<div class="box_header" id="$1"><center>$2</center></div>'
);
$str = preg_replace($format_search, $format_replace, $str);
$str = nl2br($str);
return $str;
}

将分隔符#更改为 / 。并将"/[/b']"改为"'['/b']"。您需要转义"/",因为您需要将其作为文字字符。

也许"array()"应该使用括号:"array[]"。

注意:我从这里借用了答案:使用 JavaScript/jQuery 将 BBcode 转换为 HTML

编辑

:我忘记了"/"不是元字符,所以我相应地编辑了答案。

更新:我无法让它与功能一起使用,但这个有效。请参阅评论。(我在接受的答案上使用小提琴来测试我上面链接的问题。您也可以这样做。请注意,这是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;

更新2:现在使用PHP...(抱歉,您必须根据自己的喜好格式化$replacements。我只是添加了一些标签和文本来演示更改。如果"标题"仍有问题,请查看您尝试格式化的文本类型。我用?使标题"="可选,因此它应该可以正常工作,例如:"[title=id with 一个或多个单词]Title with id[/title]"和"[title]Title without id[/title]。不确定是否允许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;