admin管理员组

文章数量:1400036

<?php
    /* ... Getting record from database */

    $ment = $record["ment"];
    /* There might be quotes or double quotes, we don't know */

    echo "<input type='button' onclick=\"doSomething('$ment')\" />";
?>

<script>
    function doSomething(ment) {
        alert(ment);

        /* Something else */
    }
</script>

When $ment string contains a single quote , I'm getting "Uncaught SyntaxError: Unexpected token ILLEGAL" error in javascript.

  • I add slashes before quotes, it didn't work - $ment = str_replace("'","\'",$ment);

How can I escape quote and double quote in this example?

<?php
    /* ... Getting record from database */

    $ment = $record["ment"];
    /* There might be quotes or double quotes, we don't know */

    echo "<input type='button' onclick=\"doSomething('$ment')\" />";
?>

<script>
    function doSomething(ment) {
        alert(ment);

        /* Something else */
    }
</script>

When $ment string contains a single quote , I'm getting "Uncaught SyntaxError: Unexpected token ILLEGAL" error in javascript.

  • I add slashes before quotes, it didn't work - $ment = str_replace("'","\'",$ment);

How can I escape quote and double quote in this example?

Share Improve this question edited May 4, 2015 at 21:00 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Nov 3, 2011 at 20:08 Okan KocyigitOkan Kocyigit 13.5k18 gold badges72 silver badges131 bronze badges 2
  • Not relevant with the php error but You're missing closing '>' of <input tag – Birey Commented Nov 3, 2011 at 20:11
  • @Birey,@Bakudan sorry i didn't copy the code, write it here, and missed the "/>" tag and a double quote. now I edited it. – Okan Kocyigit Commented Nov 3, 2011 at 20:19
Add a ment  | 

3 Answers 3

Reset to default 9

Use json_encode(), which guarantees your output will be syntactically valid JavaScript code:

<input type="button" onclick="doSomething(<?php echo json_encode($ment) ?>">

Use the PHP function addslashes().

You can try something like this in Javascript:

function addslashes(str){
    str=str.replace(//g,'\');
    str=str.replace(/'/g,''');
    str=str.replace(/"/g,'"');
    str=str.replace(//g,'');
    return str;
}
function stripslashes(str){
    str=str.replace(/'/g,''');
    str=str.replace(/"/g,'"');
    str=str.replace(//g,'');
    str=str.replace(/\/g,'');
    return str;
}

Hope this help :)

本文标签: Escaping quote in JavaScript and PHPStack Overflow