在传递给 Javascript 之前,如何在 PHP 中转义引号和已经转义的引号?
关于转义单引号和双引号有很多问题,但我没有找到解决我的特定问题的答案。
我有一个 PHP 函数,它动态返回带有 onClick 事件的图像,该事件调用 Javascript 函数,并以对象名称作为参数,如下所示:
$response = "<img src=\"images/action_delete.gif\" onClick=\"confirmDelete("'" . $event->getName() . "'")\"/>"";
Javascript 函数应在某个时刻显示确认对话框,如下所示:
confirm('Delete event ' + name + ' ?')
我应该如何格式化 $ PHP 中的响应以确保当用户输入包含 ' 或 " 或 \' 或 \" 的名称时,Javascript 确认不会混乱?
There are many questions about escaping single and double quotes but I have had no luck finding an answer that solves my particular problem.
I have a PHP function that dynamically returns an image with an onClick event that calls a Javascript function with the name of an object as an argument like so:
$response = "<img src=\"images/action_delete.gif\" onClick=\"confirmDelete("'" . $event->getName() . "'")\"/>"";
The Javascript function should display a confirmation dialogue at some point like this:
confirm('Delete event ' + name + ' ?')
How should I format $response in PHP to make sure the Javascript confirm won't mess up when the user enters a name containing ' or " or \' or \" ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 htmlspecialchars 或 htmlentities 转义 php 中的任何引号,但这并不能解决单引号的问题,即使设置了 ENT_QUOTES。
做了一些测试,我发现以下应该可以工作,尽管它可能不是很优雅:
希望有帮助
You could escape any quotes in php using htmlspecialchars or htmlentities, however this doesn't solve the issue of single quotes, even if ENT_QUOTES is set.
Doing a little testing I see the following should work, although it may not be very elegant:
Hope that helps
使用 json_encode() 处理字符串。这将确保它是一个有效的 JavaScript 表达式。
Process the string using
json_encode()
. That will ensure it's a valid JavaScript expression.非常安全的替代方案,还免费为您提供手形光标
Very safe alternative which also gives you the hand cursor for free
如果您的输入字符串中有单引号、双引号、斜杠和反斜杠,另一个解决方案对我有用:
类似于:
感谢 nicja !
Another solution worked for me, if you have single quotes, double quotes, slashs and backslashes in your input string :
with something like :
Thanks to nicja !