1

I am trying to create a preview HTML division wherein I face a challenge. When I try to get code from the textarea and print it in the HTML, I could not see the PHP code. Here's are my codes, HTML Where the code from textarea will be printed

<pre id='pques'></pre> 

jQuery code that will take value from textarea and put in the above HTML pretty print area:

jQuery(document).ready(function($) {
    setInterval(function(){
        $("#pques").html($("#eques").val());
    } 
});

Value inside the textarea with id=eques

What will be the output of the following php code? <div class="code"><?php $num = 1; $num1 = 2; print $num . "+". $num1 ; ?> </div>

Someone kindly help me to achieve this. I want somewhat similar functionality to the stack overflow question preview stuff.

Thank you.

Krishna .M
  • 85
  • 1
  • 8
  • Have a look at [this](http://stackoverflow.com/a/6234808/4202224) answer. You can use `.text()` instead of `.html()` – empiric Mar 21 '16 at 14:11
  • empiric, This looks way better. Thank you. But I want only the PHP codes to be escaped. The `
    ` must be printed as HTML and `` must be printed as PHP plain text. Might be a work with RegExp. Help me.
    – Krishna .M Mar 21 '16 at 14:21

2 Answers2

1

The simplest way to do this is to escape the angle brackets in the PHP open and closing tags as HTML entities:

<?php .. ?> becomes &lt;?php ... ?&gt; - PHP will not treat this as server code and will ignore it, but the browser will display &lt; as < and &gt; as >. This way you don't need JavaScript to do it, you can print it directly to the page. I would advise always HTML encoding any PHP code that is input on your site, and storing it with entities rather than executable code.

Kallum Tanton
  • 802
  • 7
  • 22
0

As you use jquery, you can achieve this as described here

This will escape the brackets as @kallum-tanton already pointed out.

Community
  • 1
  • 1
ndo
  • 96
  • 7