PHP How to do htmlspecialchars() when i have preg

If I'm making a forum, guestbook, comment section etc. in PHP, and someone inputs text such as hi and instead of it showing up in red, it shows up as raw text. I've tried using htmlentites() and htmlspecialchars() but the thing is I'm doing a preg_replace() to replace bbcode tags as html tags, like a forum system. If i use htmlspecialchars() before the replace, it doesn't work. However, if I use htmlspecialchars() after the replace, it displays the html tags that i converted as raw text.

<html>
<head>
<title>BBCODE TEST</title>
<link rel=stylesheet href="bbcode.css" />
<script type="text/javascript" src="bbcode.js"></script>
</head>
<body>
<?php
$form = "<form method='post' action=''>
<input type='textbox' class='textbox' name='textbox' onKeyPress='return check(event)'/>
<input type='submit' class='submit' name='submit' value='Submit' />
</form>";

if (isset($_POST['submit']) && isset($_POST['textbox'])){

$text = $_POST['textbox'];
$text = bbcode($text);

echo $text;
echo $form;
} else {
echo $form;
}

function bbcode($text){

$text = $_POST['textbox'];

$patterns = array(
"/[url=(.+)](.*)[/url]/is" => "<a href='1'>2</a>",
"/[img](.+)[/img]/is" => "<img src='1' />",
"/[b](.+)[/b]/is" => "<b>1</b>",
"/[i](.+)[/i]/is" => "<i>1</i>",
"/[u](.+)[/u]/is" => "<u>1</u>",
"/[color=(.+)](.*)[/color]/is" => "<font color='1'>2</font>"
);

foreach($patterns as $pattern => $replace){
$text = preg_replace($pattern, $replace, $text);
}

return $text;

}


?>
</body>
</html>
链接地址: http://www.djcxy.com/p/29878.html

上一篇: PHP正则表达式找到没有被另一个BBCode包围的BBCode

下一篇: PHP当我有preg时如何做htmlspecialchars()