如何为Javascript array()使用准备PHP变量?

Let's say that we have input field or textarea where user can put anything. This means that user can put there:

  • text
  • white spaces
  • multilines
  • HTML tags
  • single and double quotes
  • slashes
  • and whatnot...

My current code does this: <?php $data = addslashes($content_of_input); ?>

and soon after that...

<?php
    $php_generate_javascriptArray .='
        javascriptArray[0] ="'.$data.'";
    ';
?>
<script>
    javascriptArray = [];
    <?php echo $php_generate_javascriptArray; ?>
</script>

Adding slashes unfortunately isn't enough - Javascript breaks when user puts for instance multiple lines or HTML links into that. Is there any way to prevent that and still ALLOW Javascript array to contain LINK, MULTIPLE LINES, HTML TAGS? I'm looking for some universal filters.

json_encode will convert a PHP data structure (or string, or number) to the appropriate JavaScript data structure while making it safe for injecting into a script element in an HTML document (by escaping slashes).

<script>
    var data = <?php echo json_encode($data); ?> ;
</script>

Use PHP function urlencode(...) or base64_encode(...) of need of more advanced protection.

I normal use urlencode and on Javascript side use unescape for decode the URL format data.