Jump to content

Using htmlspecialchars


HFD

Recommended Posts

Hi, I am currently coding a system where I can have administrators of my website post up content that is posted onto the website - a lot of the time, it may be required to output HTML code as plain text, so using htmlspecialchars would be helpful. However, I want the administrators to also be able to use HTML, so I'm hoping I can do the following:

 

[nobbc]When the user enters

(code here)

(like BBCode), it'll convert the 'code' tags to HTML DIV tags, so all the code can be in a DIV container which would be stylized using CSS. I have a very vague idea on how to accomplish this, using replace functions etc....but how would I make everything between the

 tags into a variable, so I can apply htmlspecialchars on it?

Thanks [/nobbc]

Link to comment
https://forums.phpfreaks.com/topic/121763-using-htmlspecialchars/
Share on other sites

You'd use preg_replace to do this, using [tt]\

[code\](.*?)\[/code\][/tt] as the regex pattern, eg
<style type="text/css">
.code {
   white-space: pre;
   font-family: Courier New;
   border: 1px solid #333;
   background-color: #EEE;
   padding: 10px;
}
</style>
<?php

$text = <<<TEST

<h1>HTML Tutorial</h1>

<p>You should start every HTML page with:
[code]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
 <title></title>
</head>

<body>

</body>

</html>[ /code]</p>

<b>Unaffected <i>HTML</i></b>

TEST;

$text = preg_replace('#\[code\](.*?)\[/code\]#ies', "'<div class=\"code\">'.htmlspecialchars('$1').'</div>'", $text);

echo $text;

?>

 

NOTE: change [nobbc]</html>[ /code]</p> to </html>[/code]</p> (forum was messing up my post)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.