本文介绍了如何逃避只有单引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些使用用PHP呈现的字符串的JavaScript代码。我如何在PHP字符串中避免单引号(只有单引号)?

 < script type =text / javascript > 
$('#myElement')。html('say hello to<?php echo $ mystringWithSingleQuotes?>');
< / script>


解决方案

很简单: echo str_replace ('\'','\\\\'',$ myString);
但是,我建议使用和功能会更可靠(例如引用新行):

 <?php $ data = array('myString'=>'...'); ?> 

< script>
var phpData =<?php echo json_encode($ data)?> ;;
alert(phpData.myString);
< / script>


I am writing some javascript code that uses a string rendered with PHP. How can I escape single quotes (and only single quotes) in my PHP string?

<script type="text/javascript">
    $('#myElement').html('say hello to <?php echo $mystringWithSingleQuotes ?>');
</script>
解决方案

Quite simply: echo str_replace('\'', '\\\'', $myString);However, I'd suggest use of JSON and json_encode() function as it will be more reliable (quotes new lines for instance):

<?php $data = array('myString' => '...'); ?>

<script>
   var phpData = <?php echo json_encode($data) ?>;
   alert(phpData.myString);
</script>

这篇关于如何逃避只有单引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 16:51