bbcode タグの解析に nbbc.sourceforge.net を使用しています。ここで確認できる実際の問題: Github. NBBCの問題#1。
プログラミング言語の bbcode を含むテキストを解析しているとき、たとえば php のルールは、php bbcode タグを pre タグに置き換えます。
$bb = new BBCode;
$bb->AddRule('php',array(
'simple_start'=>'<pre>',
'simple_end'=>'</pre>',
'allow_in'=>false,
));
通常の行を分割する pre に空の行があります。これは次の図です。
私が使用する場合$bb->SetIgnoreNewlines(true);
、改行は前にないテキストには存在しません。それを修正する方法は?
<!DOCTYPE html">
<html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>NBBC</title>
</head>
<body>
<style>
pre { margin: 2px; border: 1px solid #c2c2c2; width: 400px; }
div.content { border: 4px dotted #27BFC5; margin: 2px; padding: 4px; width: 407px; }
</style>
<?php
require_once('nbbc-master/nbbc.php');
$bb = new BBCode;
// $bb->SetIgnoreNewlines(true);
$bb->AddRule('php',array(
'simple_start'=>'<pre>',
'simple_end'=>'</pre>',
'allow_in'=>false,
));
echo '<div class="content">'.$bb->Parse($_POST['content']).'</div>';
?>
<!-- Content for test, just copy it into the textarea
Test new lines in code
While it work.
Great!
[php]
$a ="test A";
$b =$a;
$c =$b;
[/php]
End Tests!
-->
<form action="" method="post">
<textarea name="content" cols="50" rows="13"></textarea> <br />
<input type="submit" value="submit" name="submit" />
</form>
</body>
</html>
更新 (1)
コールバックを使用しようとしました:
$content = preg_replace_callback('/(.*\[php\])(.*)(\[\/php\])(.*)/is',function($matches){
return trim($matches[1]).str_replace("\n\n","\n",trim($matches[2])).trim($matches[3]).trim($matches[4]);
},$_POST['content']);
しかし、これらはとにかくそこに壊れます:
更新し (2)
ます。まあ、これは私がやったことですが、これが最終的な解決策だとは思いません:
$bb = new BBCode;
// $bb->SetIgnoreNewlines(true);
$bb->AddRule('php',array(
'simple_start'=>'<pre>',
'simple_end'=>'</pre>',
'allow_in'=>false,
));
$content = preg_replace_callback('/(.*\[php\])(.*)(\[\/php\].*)/is',
function ( $matches ) { return $matches[1].trim($matches[2]).$matches[3]; }
,$_POST['content']);
$content = $bb->Parse($_POST['content']);
$content = preg_replace_callback('/(.*<pre>)(.*)(<\/pre>.*)/is',
function ( $matches ) { return trim($matches[1]).preg_replace('/<br \/>/is','',trim($matches[2])).trim($matches[3]); }
,$content);
echo '<div class="content">'.$content.'</div>';
NBBC ライブラリの場合、この問題は保留中です。
これに基づいて更新 (3)
します:
$content = $bb->Parse($content);
$content = preg_replace_callback('/(.*<pre.*?>)(.*)(<\/pre>.*)/is',
function ( $matches ) {
return trim($matches[1]).str_replace('<br />','',trim($matches[2])).trim($matches[3]);
}
,$content);