问题
I want to securely display codes on my website. I am using Bootstrap on front end and PHP on server side.
My site has a comment box.
If I enter something as following then the whole webpage gets distorted. I want to detect that the text is a code and display it with a greyish background just like Stack Overflow.I am creating a blog like website in which on the home page I am displaying first 300 characters. So if I use code tag then the opening tag remains there but there is no closing tag and I end up distorting my website. I am also trying to integrate text editors like TinyMCE and CKEditor.
<div class="text-muted">
回答1:
You can try the use of pre
and HTML entites and apply some CSS for styling:
pre {
border:1px solid #ccc;
padding:10px;
background:linear-gradient(#eff0f1,#eff0f1) 8px 8px/calc(100% - 16px) calc(100% - 16px) no-repeat;
}
<pre>
<a class="link"> this a link </a>
<p> this some content </p>
</pre>
then you can consider some JS if you want to automatically change the <
>
let content = $('pre').html();
content = content.replace(/</g, '<');
content = content.replace(/>/g, '>');
$('pre').html(content);
pre {
border: 1px solid #ccc;
padding: 10px;
background: linear-gradient(#eff0f1, #eff0f1) 8px 8px/calc(100% - 16px) calc(100% - 16px) no-repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<pre>
<div class="container" data-attr="some data">
<img src="https://lorempixel.com/400/200/" >
<a class="link"> this a link </a>
<p> this some content </p>
</div>
</pre>
These are very simplified examples and you can find on the net many library that allow you to apply advanced styling:
回答2:
You can use <pre></pre>
or <code></code>
Tags to wrap your code samples. Then you insert your code with PHP between the tags. Be careful to escape all html tags - in PHP you can use htmlentities() to escape your output.
http://php.net/manual/de/function.htmlentities.php
<?php
$code = "<p>This is some <b>html</b> code";
// safely display the code in the website:
echo("<pre>" . $code . "</pre>");
?>
If you prefer something more sophisticated (like systax highlighting), have alook at this open-source solution: https://ace.c9.io/
来源:https://stackoverflow.com/questions/48719488/how-to-display-a-piece-of-code-on-my-website-like-the-way-stack-overflow-does