10c07-1.php
来自「介绍PHP5的给类型函数应用」· PHP 代码 · 共 75 行
PHP
75 行
<?php// A function to format BBCode. It current translates the following:// [b] = <b>, [i] = <i>, [code] = <pre>,// [quote] = <blockquote><i>, [img] = <img>// It also turns double-carraige returns, into appropriate whitespacefunction format_bbcode($string) { // Define some direct translations: $trans = array( 'b' => 'b', 'i' => 'i', 'code' => 'pre' ); // Using regex to find bbcode, and loop over the string: // It is necessary to loop, to handle code within code. // This regex looks for [word], followed by anything up to [/word] while (preg_match('|\[([a-z]+)\](.*?)\[/\1\]|', $string, $r, PREG_OFFSET_CAPTURE)) { // So at this point [0][0] contains the full matched string. // [0][1] contains the offset position of that string // [1][0] is the second match, which is our tag name. // [2][0] is the 3rd match, the tag contents // So now, based upon the tag, implement the HTML // If this is a direct translation tag: if (isset($trans[$r[1][0]])) { // Simply replace with HTML tag version: $replace = "<{$trans[$r[1][0]]}>{$r[2][0]}</{$trans[$r[1][0]]}>"; } // Special case: quote elseif ($r[1][0] == 'quote') { // Replace with two tags: $replace = "<blockquote><i>{$r[2][0]}</i></blockquote>"; } // Special case: img elseif ($r[1][0] == 'img') { // Create an image tag using the contents. $replace = "<img src=\"{$r[2][0]}\" />"; } else { // If we found any other tag, consider it invalid, and strip it: $replace = $r[2][0]; } // Now, perform the actual replacement $string = substr_replace($string, $replace, $r[0][1], strlen($r[0][0])); } // One last step, replace any double-carraige returns, with a // paragraph break, make it work for both Windows servers: $string = str_replace("\r\n\r\n", '</p><p>', $string); // And unix: $string = str_replace("\n\n", '</p><p>', $string); // Now return the whole string, surrounded by paragraph tags: return "<p>{$string}</p>";}// If we had a POST, then output the data for reference:if (count($_POST)) { // Strip the data of special characters, and then BBCode it: $bbcode = format_bbcode(htmlspecialchars($_POST['data'])); // Show as code: echo "<p>The BBCode source:</p>\n"; echo '<p>', htmlspecialchars($bbcode), "</p>\n"; // Display it: echo "<p>The BBCode displayed:</p>\n"; echo $bbcode;}?><form action="<?= $_SERVER['PHP_SELF'] ?>" method="post" name="f1"><p>Enter some data:</p><p><textarea name="data" cols="80" rows="10"><?= @$_POST['data'] ?></textarea></p><p><input type="submit" /></p></form>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?