简体   繁体   English

如何在 PHP json_encode 中转义撇号

[英]How escape apostrophe in PHP json_encode

I am passing a json_encode object into a button.我将 json_encode object 传递到按钮中。

 <button aria-controls="web-share-fallback" aria-expanded="false"
    class="c-share__link btn-link underline font-normal"
    data-js="web-share track" data-web-share='{{
    post.getWebShare()|json_encode }}' data-track-key="Web Share" data-track-data='[{"action": "web-share"}]'>

Now getWebShare() returns an array which seems to be breaking in the following string.现在getWebShare()返回一个似乎在以下字符串中中断的数组。 在此处输入图像描述

The word can't seems to be causing the string to end which prevent the button from firing up.这个词似乎can't导致字符串结束,从而阻止按钮启动。 json_encode doesn't seem to be solving this. json_encode似乎没有解决这个问题。

  public function getWebShare() {
    foreach ($this->web_share as &$value) {
      $value = addslashes($value);
    }
    return $this->web_share;
  }

The method addslashes does seem to be adding the \ to the can't word trying to scape it but it still breaking the full string as shown in the image above. addlashes方法似乎确实将\添加到can't单词中试图对其进行转义,但它仍然会破坏完整的字符串,如上图所示。

How can I go about the string from closing on the single apostrophe?我怎样才能 go 关于关闭单个撇号的字符串?

The function json_encode only encode data into valid JSON format. function json_encode仅将数据编码为有效的 JSON 格式。 To use a JSON string (or any string for that matter) as a valid HTML tag attribute, you should use htmlspecialchars or equivlant way to treat it.要使用 JSON 字符串(或任何字符串)作为有效的 HTML 标记属性,您应该使用htmlspecialchars或等效的方式来处理它。

Twig's escape filter should work for your case. Twig 的逃生过滤器应该适用于您的情况。

<button aria-controls="web-share-fallback" aria-expanded="false"
    class="c-share__link btn-link underline font-normal"
    data-js="web-share track" data-web-share='{{
    post.getWebShare()|json_encode|escape }}' data-track-key="Web Share" data-track-data='[{"action": "web-share"}]'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM