简体   繁体   中英

Escaping quote in JavaScript and PHP

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

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

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

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

        /* Something else */
    }
</script>

When $comment 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 - $comment = str_replace("'","\\'",$comment);

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

使用json_encode() ,以确保您的输出在语法上是有效的JavaScript代码:

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

使用PHP函数addlashes()

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM