我正在编写一些JavaScript代码,该代码使用PHP渲染的字符串。如何在PHP字符串中转义单引号(和仅单引号)?
<script type="text/javascript"> $('#myElement').html('say hello to <?php echo $mystringWithSingleQuotes ?>'); </script>
很简单:echo str_replace('\'', '\\\'', $myString); 但是,我建议使用JSON和json_encode()函数,因为它会更可靠(例如,引用新行):
echo str_replace('\'', '\\\'', $myString);
json_encode()
<?php $data = array('myString' => '...'); ?> <script> var phpData = <?php echo json_encode($data) ?>; alert(phpData.myString); </script>