Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape " character in php with echo [duplicate]

Tags:

html

php

escaping

Short question:

echo '<button type="button" id="add" onClick="addAsset('.$filename.');"> '.$filename.' </button>';

this creates a button with an onClick function addAsset(example.png); But i'd like to have addAsset("example.png") how do i escape the " character?

Thank you!

like image 528
vldn Avatar asked Oct 23 '25 04:10

vldn


1 Answers

The end result you'll want to end up with is:

<button type="button" id="add" onClick="addAsset(&quot;example.png&quot;);"> example.png </button>

Otherwise you'll have broken HTML syntax. The alternative is non-conflicting quotes:

<button type="button" id="add" onClick="addAsset('example.png');"> example.png </button>

But you'll still have to escape/encode your input correctly, in case $filename ever contains an undesirable character. The value of the onClick attribute must be valid Javascript, and valid HTML. So:

printf('<button type="button" id="add" onClick="%s"> %s </button>',
       htmlspecialchars(sprintf('addAsset(%s)', json_encode($filename))),
       htmlspecialchars($filename));
like image 58
deceze Avatar answered Oct 25 '25 19:10

deceze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!