How to escape a string with single quotation marks in PHP?

the string entered by the user in the database is displayed as Mike"s,PHP output. JS will report a syntax error in the web page, indicating that Uncaught SyntaxError: Unexpected identifier, is obviously caused by one more".

Page error output code

<script>
    var html = "<select><option>Mike"s</option></select>";
</script>

obviously there is a conflict between quotation marks and js, which can be solved temporarily with double quotes, but some users will also enter double quotation marks, so is there any good solution here that can completely solve this problem?

Apr.05,2021

<script>
    var html = '<select><option>Mike\'s</option></select>';
</script>

solve the problem within php

str_replace("'", "/'", $str);

solve the problem in js, of course, if the user enters `, it will also report an error. It's better to deal with it in php

.
var html = `<select><option>Mike's</option></select>`;

escape with backslash:

'Mike\'s'

you can also use double quotes:

"Mike's"

double quotes are not escaped in single quote string , and single quotation marks are not escaped in double quote string .

but note that there is a slight difference between single quotation marks and double quotation marks. For example, variables can be used directly in double quotation marks:

$a='Mike';
"$a's";    //Mike's

there are also more escape characters that can be used in double quotes, such as \ n line breaks, and so on.

the user enters without processing , because it has been processed internally in PHP, where the single quotation marks are characters and will not be paired with the single quotation marks as a language structure.

$a='Mike\'s';    //Mike'sMike\'s

$b="Mike\"s";    //Mike"sMike\"s

$c="something $b";    //$b

if you want to put it in the js code, you can use the addslashes function to deal with it. Please check the documentation for details.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1ea6a68-69564.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1ea6a68-69564.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?