I have a JSON string which is like this when I log it:
..."items":{"0":"
\t\t\t\t\t"},"buys":{"0":"
\t\t\t\t\t"}}}, "sells":{}, "clients":{"test":{"0":"
\t\t\t\t"}...
What I want is to delete all new line feed (\n) & tab characters(\t) from it and have a JSON string like this :
..."items":{},"buys":{}}}, "sells":{}, "clients":{"test":{}...
I have written a preg_replace function like this :
$json = preg_replace(['/\"0\"\:\n\"[\\t]+/'], [''], $json);
but When I log the JSON string they have not been deleted .
What should I do ?
You can use str_replace() function to replace the \t and \n:
$json = str_replace(array('\t','\n'),'',$json);
You can read more about this here.
You may use this regular expression "[\t\n\r]"
Related
Currently i am facing issue of replace string , I used postman & passing string in postman like [{"id":"115","flag":"1","qty":"3","size":"10"}] as a parameters but when i print string i am getting output like [{\"id\":\"115\",\"flag\":\"1\",\"qty\":\"3\",\"size\":\"10\"}] , So i want to only remove '\' from string i have tried following code but not work.
$fliesid_in_store = $_REQUEST['fliesid_in_store'];
echo $res = preg_replace("/[^a-zA-Z]/", "", $fliesid_in_store);
Have you tried stripslashes.
$fliesid_in_store = $_REQUEST['fliesid_in_store'];
echo stripslashes($fliesid_in_store);
The string you mentioned is in json format
$json = [{"id":"115","flag":"1","qty":"3","size":"10"}] //this is json
Assign that to variable and decode it.
$string = json_decode($json,TRUE) this give result in array format
In your case
$string = json_decode($_REQUEST['fliesid_in_store'],TRUE);
I working at PHP Project With PHP Version 7.0.13
I was dealing with JSON lately, I have a JSON file that needs to be decode to PHP but before I decode the JSON, I need to clean some abstract string inside the file that JSON obtained inside, to clean the string using substr() to get the JSON.
when i write the code, like this:
$jsonraw = "\"{ JSON should be here, later }\"";
$cutstart = strpos($jsonraw, "{");
$cutend = strrpos($jsonraw, "\"");
$jsonclean = substr($jsonraw, $cutstart, $cutend);
echo $jsonclean;
The output is like this
{ JSON should be here, later }
But when the string is like this
$jsonraw = "\"some abstract string to remove { JSON should be here, later }\"";
The output is became like this
{ JSON should be here, later }"
As we can see there was a quote symbol " at the last of the string, I was trying to decrement the $cutend, like this $jsonclean = substr($jsonraw, $cutstart, --$cutend); and this to $cutend-1
Any help, I appreciate.
Sorry for my bad English
You can use preg_match to get the json from that string:
$string = "some abstract string to remove { JSON should be here, later }";
preg_match('/\{.*\}/', $string, $match);
var_dump($match[0]);
the result would be:
string(30) "{ JSON should be here, later }"
As the third parameter is the length of the string, you need to say that the length is the end position minus the start position...
$jsonclean = substr($jsonraw, $cutstart, $cutend-$cutstart);
I have a (simplified) JSON response from an API call that looks like below
{"status":true,"action_values":"{\n \"range_from\": \"0\",\n \"range_to\": \"0\"\n}"}
I am trying to remove the \n characters from above using PHP but it doesn't seem to be working.
I try:
$trimmed = str_replace("\n", "", $response);
Where $response is my JSON string as above. But this does not remove/replace the \n character.
There is no need to remove the \n / new-lines.
Instead you should decode your string using json_decode() and then you can decode the range_from value, which is also json encoded inside your original json:
<?php
$str = '{"status":true,"action_values":"{\n \"range_from\": \"0\",\n \"range_to\": \"0\"\n}"}';
$dec = json_decode($str, true);
var_dump(json_decode($dec['action_values'], true));
Result:
array(2) {
["range_from"]=>
string(1) "0"
["range_to"]=>
string(1) "0"
}
An example.
I would recommend the solution by #jeroen, since it makes use of PHPs native functions to handle JSON.
However, since you've asked, I sense that you do not completely understand why your solution did not work.
As already pointed out in the comments by #B001 you need "\\n" for this task:
$trimmed = str_replace("\\n", "", $response);
The reason for this is, that "\n" represents the new line character when "\\n" represents the string "\n".
Try the following code and you will see the difference
print("-----");
print("\n");
print("-----");
print("\\n");
print("-----");
print("\"");
Which will result in the following output:
-----
-----\n-----"
The reason for this is that every instance of the "\" character in code, starts a control character. Examples for this are "\n" for newline, "\r" for carriage return, "\t" for tab, \" for the "-character inside a string defined by "" and "\\" for the actual backslash-character.
So if you want to create the actual string containing \n, you have to tell the interpreter that you actually want the \-character and not a control character created by \ and what ever character follows. This is done by using double backslashes "\\" which is the string representation of the actual backslash string. This is called "escaping".
In your case you have the actual character string in your $response variable, and you therefore have to use the escaped character as pattern.
Last let me explain the difference between "\n" and '\n'.
There are two ways in PHP to create a string:
$str1 = "hello \n world\n";
$str2 = 'hello \n world\n';
print($str1);
print($str2);
Both variables will contain a string, however, the "-string indicates for the PHP interpreter that the contained string should be interpreted, while the '-string gives you the string as it is. The example above would therefor result in the following output:
hello
world
hello \n world\n
This shows that the following code also would strip your string of the \n instances since '\n' would contain the actual string and not the control character:
$trimmed = str_replace('\n', "", $response);
This interpretation of the "-string goes so far as to allow for variables to be inserted into a string:
$name = "Daniel";
$age = 18;
$sentence = "My Friend $name is $age years old.";
print($sentence);
and would result in:
My Friend Daniel is 18 years old.
I want to parse some json response into php array, the problem is nginx push stream module response with not separated json string, is possible to parse this without using regex?
'{"id":1,"channel":"1","text":"Hello World!"}{"id":2,"channel":"1","text":"Hello World!"}{"id":2,"channel":"1","text":{"key_x": "value_x"}}'
Edit
The real issue was that nginx push-stream module send archive in stream, so thats why there is no separator between json data in my snippet.
$str = '{"id":1,"channel":"1","text":"Hello World!"}{"id":2,"channel":"1","text":"Hello World!"}{"id":2,"channel":"1","text":"Hello World!"}';
$str = str_replace('}{', '},{', $str);
$str = '[' . $str . ']';
print_r(json_decode($str));
https://3v4l.org/BNVTg
I dont think this is actually possible without either changing the output or use regex / str_replace.
If you have control over the output you should change the output to valid json:
{"data":[
{"id":1,"channel":"1","text":"Hello World!"},
{"id":2,"channel":"1","text":"Hello World!"},
{"id":2,"channel":"1","text":"Hello World!"}
]}
It you cant do this then you could try to use str_replace with explode:
$data = str_replace('}{', '}<should_be_absolut_unique>{');
foreach( explode('<should_be_absolut_unique>', $data) as $json ){
# json_decode($json)
}
This is of course very unsave and not guaranteed to work because you dont know if the string replace works correctly if you do not know the data that is send!
I need to grab a json-string from this page: https://retracted.com
If you view the source, I json-string starts after var mycarousel_itemList =. I need to parse this string as a correct json-array in my php-script.
How can this be done?
EDIT: I've managed to pull this off using explode, but the method is ugly as heck. Is there no build-in function to translate this json-string to a array?
To clarify: I want the string I grab (which is correct json) to be converted into a php-array.
The JSON in the script block is invalid and needs to be massaged a bit before it can be used in PHP's native json_decode function. Assuming you have already extracted the JSON string from the markup (make sure you exclude the semicolon at the end):
$json = <<< JSON
[ { address: 'Arnegårdsveien 32', … } ]
JSON;
var_dump(
json_decode(
str_replace(
array(
'address:',
'thumb:',
'description:',
'price:',
'id:',
'size:',
'url:',
'\''
),
array(
'"address":',
'"thumb":',
'"description":',
'"price":',
'"id":',
'"size":',
'"url":',
'"'
),
$json
)
,
true
)
);
This will then give an array of arrays of the JSON data (demo).
In other words, the properties have to be double quoted and the values need to be in double quotes as well. If you want an array of stdClass objects instead for the "{}" parts, remove the true.
You can do this either with str_replace as shown above or with a regular expression:
preg_match('
(.+var mycarousel_itemList = ([\[].+);.+function?)smU',
file_get_contents('http://bolig…'),
$match
);
$json = preg_replace(
array('( ([a-z]+)\:)sm', '((\'))'),
array('"$1":', '"'),
$match[1]
);
var_dump(json_decode($json, true));
The above code will fetch the URL, extract the JSON, fix it and convert to PHP (demo).
Once you have your json data, you can use json_decode (PHP >= 5.2) to convert it into a PHP object or array