如何仅转义单引号? [英] How do I escape only single quotes?

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

问题描述

我正在编写一些JavaScript代码,该代码使用PHP渲染的字符串.如何在PHP字符串中转义单引号(和仅单引号)?

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>

推荐答案

很简单:echo str_replace('\'', '\\\'', $myString); 但是,我建议使用 JSON

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>

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆