IT Blog

  • Blog
  • Technology
    • Technology
    • Architecture
    • CMS
    • CRM
    • Web
    • DotNET
    • Python
    • Database
    • BI
    • Program Language
  • Users
    • Login
    • Register
    • Forgot Password?
  • ENEN
    • 中文中文
    • ENEN
Experience IT
In a World of Technology, People Make the Difference.
  1. Home
  2. Technology
  3. Program Language
  4. PHP
  5. Escape JSON Special Characters using PHP

Escape JSON Special Characters using PHP

2018-05-22 1523 Views 0 Like 0 Comments

Table of Contents

  • Escape JSON Special Characters using PHP
    • php > 5.2
    • php versions older that 5.2
    • result

Escape JSON Special Characters using PHP

php > 5.2

$str_valid=json_encode($str);

php versions older that 5.2

/**
 * @param $value
 * @return mixed
 */
function escapeJsonString($value) { # list from www.json.org: (\b backspace, \f formfeed)
    $escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
    $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
    $result = str_replace($escapers, $replacements, $value);
    return $result;
}

result

{"message":"\\"}  =>  {\"message\":\"\\\\\"}
{\"message\":\"\\\\\"}

use the json_encode constant JSON_HEX_APOS as the second parameter which will convert all single quotes ' to \u0027. :

var t = <?php echo json_encode($data,JSON_HEX_APOS);?>;

Loading

error
fb-share-icon
Tweet
fb-share-icon
IT Team
Author: IT Team

Tags: None
Last updated:2018-05-22

IT Team

This person is lazy and left nothing

Like
Next >

Comments

Cancel reply
Newest Hotspots Random
Newest Hotspots Random
Rich editor not working Making web page scroll down automatically Getting data from Dapper result All Unicode Chars How to keep and display contact form 7 data Common Regular Expressions
Show any data in DataTables in WordPress Send report in the attachment from database Symbols: Stars Covid-19 open data How to auto-move to the bottom of a block Query menu in WordPress
Categories
  • Architecture
  • BI
  • C#
  • CSS
  • Database
  • DotNET
  • Hosting
  • HTML
  • JavaScript
  • PHP
  • Program Language
  • Python
  • Security
  • SEO
  • Technology
  • Web
  • Wordpress

COPYRIGHT © 2021 Hostlike IT Blog. All rights reserved.

This site is supported by Hostlike.com