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.
Related
i have a PHP scripts that removes special characters, but unfortunately, some Chinese characters are also removed.
<?php
function removeSpecialCharactersFromString($inputString){
$inputString = str_replace(str_split('#/\\:*?\"<>|[]\'_+(),{}’! &'), "", $inputString);
return $inputString;
}
$test = '赵景然 赵景然';
print(removeSpecialCharactersFromString($test));
?>
oddly, the output is 赵然 赵然. The character 景 is removed
in addition, 陈 一 is also removed. What might be the possible cause?
The string your using to act as a list of the things you want to replace doesn't work well with the mixed encoding. What I've done is to convert this string to UTF16 and then split it.
function removeSpecialCharactersFromString($inputString){
$inputString = str_replace(str_split(
mb_convert_encoding('#/\\:*?\"<>|[]\'_+(),{}’! &', 'UTF16')), "", $inputString);
return $inputString;
}
$test = '#赵景然 赵景然';
print(removeSpecialCharactersFromString($test));
Which gives...
赵景然赵景然
BTW -str_replace is MB safe - sort of recognised the poster... http://php.net/manual/en/ref.mbstring.php#109937
I know this question asked here many times.But That solutions are not useful for me. I am facing this problem very badly today.
// Case 1
$str = 'Test \300'; // Single Quoted String
echo json_encode(utf8_encode($str)) // output: Test \\300
// Case 2
$str = "Test \300"; // Double Quoted String
echo json_encode(utf8_encode($str)) // output: Test \u00c0
I want case 2's output and I have single quoted $str variable. This variable is filled from XML string parsing . And that XML string is saved in txt file.
(Here \300 is encoding of À (latin Charactor) character and I can't control it.)
Please Don't give me solution for above static string
Thanks in advance
This'll do:
$string = '\300';
$string = preg_replace_callback('/\\\\\d{1,3}/', function (array $match) {
return pack('C', octdec($match[0]));
}, $string);
It matches any sequence of a backslash followed by up to three numbers and converts that number from an octal number to a binary string. Which has the same result as what "\300" does.
Note that this will not work exactly the same for escaped escapes; i.e. "\\300" will result in a literal \300 while the above code will convert it.
If you want all the possible rules of double quoted strings followed without reimplementing them by hand, your best bet is to simply eval("return \"$string\""), but that has a number of caveats too.
May You are looking for this
$str = 'Test \300'; // Single Quoted String
echo json_encode(stripslashes($str)); // output: Test \\300
I'm a designer trying to upgrade myself into a coder-designer. Lately I've been looking into some PHP codes and manuals, then I ran into an example code for the eval() function :
<?php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
?>
This is an example code of eval() function in official PHP website, and although it did help me understand the eval() function, I can't figure out how the example code works. to be more specific, I can't understand why
("\$str = \"$str\";")
results in a merged string.
I really can't figure out why this should work.
Ok, here is what we have:
eval("\$str = \"$str\";")
Look, the string is in double quotes: it means that the $ character will be interpreted as a variable start. So we screen this character with a backslash: \$, then it will "mean" just a normal dollar sign. Also, the double quotes inside the string had to be screened too.
In the end we are getting this string: (I changed the quotes to single so $ dont confuse you): '$str = "$str";'. Look, it looks more like a normal code now :)
Evaling it, PHP will do the following (I removed the outer quotes for convenience):
eval( $str = "$str" );
Notice the double quotes here, too. It means that the variable inside, again, will be parsed/interpreted.
As $str was originally == 'This is a $string with my $name in it.', it will be inserted into the expression, and now it will look like:
$str = "This is a $string with my $name in it.";
And, again, double quotes! It parses and substitutes variables $name and $string, giving us at the end:
$str = "This is a cup with my coffee in it."
Voila!
A mindbreaker, but a really good example to learn the mechanisms.
you should get two console.log like this
This is a $string with my $name in it.';
This is a $cup with my $coffe in it.';
Why? well first you print the value, of $str , without eval, and later, you eval them, basically this happens,
First.
Print $str, without eval.
This is a $string with my $name in it.';
Second
this piece of code, runs eval("\$str = \"$str\";");
Eval replace $string and $name. with the 2 new variables values, which are $cup and $coffe
Hope you get it
When renumbering an array using
$arr=array_values($arr); // Renumber array
I realized that a line break is being introduced into one of the array strings, which I don't want.
My string is going from:
Property
Type
to Property
Type
In any case I am using:
$newelement = preg_replace("/[^A-Za-z0-9\s\s+]/", " ", $element);
already to remove unwanted characters prior to database insertion, so I tried to change it to:
$newelement = preg_replace("/[^A-Za-z0-9\s\s+'<br>''<br>''/n''/cr']/", " ", $element);
But there is no change, and the ?line feed/line break/carriage return is still there.
Am I doing the preg_replace call correctly?
That preg looks a bit complicated. And then you have ^ in the beginning as not A-Z... or linefeed. So you don't want to replace linefeed?
How about
$newelement = preg_replace("/[\n\r]/", "", $element);
or
$newelement = preg_replace("/[^A-Za-z ]/", "", $element);
\s also matches linefeed (\n).
This should work too:
// char(32) is whitespace
// For CR
$element = strtr($element, chr(13), chr(32));
// For LF
$element = strtr($element, chr(10), chr(32));
This thing worked for me.
preg_replace("/\r\n\r\n|\r\r|\n\n/", "<br />", $element);
It's a hack, but you can do something like this:
$email_body_string = preg_replace("/\=\r\n$/", "", $email_body_string);
The replacement says find a line that ends with an equals sign and has the standard carriage return and line feed characters afterwards. Replace those characters with nothing ("") and the equals sign will disappear. The line below it will be pulled up to join the first line.
Now, this implies that you will never have a line that ends with an equals sign, which is a risk. If you want to do it one better, check the line length where the wrap (with the equals sign) appears. It's usually about 73 characters in from the beginning of the line. Then you could say:
if (strlen(equals sign) == 73)
$email_body_string = preg_replace("/\=\r\n$/", "", $email_body_string);
<?php
include 'db_connect.php';
$q = mysql_real_escape_string($_GET['q']);
$arr = explode('+', $q);
foreach($arr as $ing)
{
echo $ing;
echo "<br/>";
}
mysql_close($db);
?>
Calling:
findByIncredients.php?q=Hans+Wurst+Wurstel
Source code HTML:
Hans Wurst Wurstel<br/>
Why is there only one newline?
+s in URL are urlencoded spaces. So what php sees in the variable is "Hans Wurst Wurstel". You need to split by space ' ', not +
arr = explode (' ',$q);
"+" gets converted to SPACE on URL decoding.
You may want to pass your string as str1-str2-str3 in get parameter.
Try:
<?php
include 'db_connect.php';
$q = mysql_real_escape_string($_GET['q']);
$arr = explode (' ',$q);
foreach($arr as $ing)
{
echo $ing;
echo "<br/>";
}
mysql_close($db);
?>
Hans+Wurst+Wurstel is the url escaped query string. The php page will likely process it once unescaped (in this case, all +s will be translated into spaces). You should choose a delimiter for explode according to the string as it is in that moment. You can use print_r() for a raw print if you don't know how the string (or any kind of variable) looks like.
Easy. While the standard RFC 3986 url encoding would encode the space " " as "%20", due to historical reasons, it can also be encoded as "+". When PHP parses the query string, it will convert the "+" character to a space.
This is also illustrated by the existence of both:
urlencode: equivalent of what PHP uses internally, will convert " " to "+".
rawurlencode: RFC-conformant encoder, will convert " " to "%20".
I'm assuming you want to explode by space. If you really wanted to encode a "+" character, you could use "%2B", which is the rawurlencode version and will always work.
(EDIT)
Related questions:
When to encode space to plus (+) or %20?
PHP - Plus sign with GET query