How to display a piece of code on my website like the way Stack Overflow does? [closed]

↘锁芯ラ 提交于 2021-02-07 10:11:50

问题


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>
&lt;a class="link"&gt; this a link &lt;/a&gt;
&lt;p&gt; this some content &lt;/p&gt;
</pre>

then you can consider some JS if you want to automatically change the < >

let content = $('pre').html();
content = content.replace(/</g, '&lt;');
content = content.replace(/>/g, '&gt;');
$('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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!