0

-------------php code ends here-------------

<script type="text/javascript">
    var e = <?php echo $tweetText; ?>; 
    var f = twemoji.parse(e);
    document.write(f);
</script>

-------------php code starts here-------------

If I put single quotes or double quotes before and after then it matches any ' or " inside the tweetText and doesn't let the string print to screen.

C A
  • 87
  • 1
  • 8
  • 2
    possible duplicate of [How to assign Php variable value to Javascript variable?](http://stackoverflow.com/questions/5895842/how-to-assign-php-variable-value-to-javascript-variable) – Rizier123 Feb 24 '15 at 15:47
  • Well you have to quote that string, but I can assure that you will need to more than just echo out the tweet. There will be quotes and junk in there that will cause JavaScript errors. – Halfstop Feb 24 '15 at 15:47
  • 1
    you should use `json_encode` php function. See here http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-and-escape-newlines – Vivek Vaghela Feb 24 '15 at 15:49

4 Answers4

0
<script type="text/javascript">
    var e = '<?php echo $tweetText; ?>'; 
    var f = twemoji.parse(e);
    document.write(f);
</script>

That's it

0

This solution works fine, just add ,,addslashes" to escape quotes

<script type="text/javascript">
    var e = '<?php echo addslashes($tweetText); ?>'; 
    var f = twemoji.parse(e);
    document.write(f);
</script>
  • And what if the string has a double-quote in it? It would come out as var e = 'He said, \"Yes, that\'s it.\"'; – Halfstop Feb 24 '15 at 16:20
  • Have fun removing slashes in your code. This is not the correct solution to your problem. – Halfstop Feb 24 '15 at 16:36
0

The best way to do this would be with json_encode as @vivek said in a comment.

<script type="text/javascript">
var e = <?php echo json_encode($tweetText); ?>;
var f = twemoji.parse(e);
document.write(f);
</script>
Halfstop
  • 1,710
  • 17
  • 34
-1

Try to put the whole string inside doublequotes, then escape the same - double quotes - inside the javascript string, with a simple str function:

<script type="text/javascript">
var e = "<?php echo str_replace('"','\"',$tweetText); ?>"; 
var f = twemoji.parse(e);
document.write(f);
</script>
Balázs Varga
  • 1,797
  • 2
  • 16
  • 32