简体   繁体   中英

How escape apostrophe in PHP json_encode

I am passing a json_encode object into a button.

 <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. 在此处输入图像描述

The word can't seems to be causing the string to end which prevent the button from firing up. json_encode doesn't seem to be solving this.

  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.

How can I go about the string from closing on the single apostrophe?

The function json_encode only encode data into valid JSON format. 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.

Twig's escape filter should work for your case.

<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"}]'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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