Search code examples
phphtmljqueryparsinghtml-parsing

How to implement PHP Parser into .html() jQuery for a live preview input text


I'm trying to create a live preview for the text editor I've create, but I haven't being able to come up with a way to parser the text inside the preview div so it would change BBCodes tags (like [b][/b]) into HTML ones.

https://jsfiddle.net/ElenaMcDowell/5hzndj7v/3/

<div class="previewDocument-box">
    <h1>Preview</h1>
    <div class="previewDocument-text"></div>
</div>

<textarea id="ECEditor" class="editor-textarea" style="height: 200px;" name="editor-text"></textarea>

<script>
    $('#ECEditor').on('input', function() {
        var ECEtext = $(this).val();
        $('.previewDocument-text').html(ECEtext);
    });
</script>

EDIT: What I need is to convert the text entered in the textarea (#ECEditor), and which is later placed in a div (.previewDocument-text), into HTML. I have already a PHP function ( called "BBCode2HTML()" ) that converts BBCode to HTML (Like [b]Hi[/b] ---> Hi), but I don't know how to implement that function into the jQuery that creates a form of "live preview input". :(


Solution

  • We can replace those BBCodes tags with HTML ones

    $('#ECEditor').on('input', function() {
         var text = $(this).val();
         var bb =  [
            /\[b\](.*?)\[\/b\]/ig,
            /\[i\](.*?)\[\/i\]/ig,
            /\[u\](.*?)\[\/u\]/ig
        ];
        
        var bb_html = [
            '<b>$1</b>',
            '<em>$1</em>',
            '<u>$1</u>'
        ];
     
        for (var i =0;i<bb.length;i++) {
          text = text.replace(bb[i], bb_html[i]);
        }
         $('.previewDocument-text').html(text);
        });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="previewDocument-box">
        <h1>Preview</h1>
        <div class="previewDocument-text"></div>
    </div>
    <textarea id="ECEditor" class="editor-textarea" style="height: 200px;" name="editor-text"></textarea>

    Second method will be to send the entered value to backend through ajax and use PHP's preg_replace.

    preg_replace(['/[b]/i', '/[\/b]/i'], ['<b>', '</b>'], $text);