Replacing \r\n (newline characters) after running json_encode - php

So when I run json_encode, it grabs the \r\n from MySQL aswell. I have tried rewriting strings in the database to no avail. I have tried changing the encoding in MySQL from the default latin1_swedish_ci to ascii_bin and utf8_bin. I have done tons of str_replace and chr(10), chr(13) stuff. I don't know what else to say or do so I'm gonna just leave this here....
$json = json_encode($new);
if(isset($_GET['pretty'])) {
echo str_replace("\/", "/", jsonReadable(parse($json)));
} else {
$json = str_replace("\/", "/", $json);
echo parse($json);
}
The jsonReadable function is from here and the parse function is from here. The str_replaces that are already in there are because I am getting weird formatted html tags like </h1>. Finally, $new is an array which is crafted above. Full code upon request.
Help me StackOverflow. You're my only hope

Does the string contain "\r\n" (as in 0x0D 0x0A) or the literal string '\r\n'? If it's the former, this should remove any newlines.
$json = preg_replace("!\r?\n!", "", $json);
Optionally, replace the second parameter "" with "<br />" if you'd like to replace the newlines with a br tag. For the latter case, try the following:
$json = preg_replace('!\\r?\\n!', "", $json);

Don't replace it in the JSON, replace it in the source before you encode it.

I had a similar issue, i used:
$p_num = trim($this->recp);
$p_num = str_replace("\n", "", $p_num);
$p_num = str_replace("\r", ",", $p_num);
$p_num = str_replace("\n",',', $p_num);
$p_num = rtrim($p_num, "\x00..\x1F");
Not sure if this will help with your requirements.

Related

How to add new line in php echo

The text of story content in my database is:
I want to add\r\nnew line
(no quote)
When I use:
echo nl2br($story->getStoryContent());
to replace the \r\n with br, it doesn't work. The browser still display \r\n. When I view source, the \r\n is still there and br is nowhere to be found also. This is weird because when I test the function nl2br with simple code like:
echo nl2br("Welcome\r\nThis is my HTML document");
it does work. Would you please tell me why it didn't work? Thank you so much.
The following snippet uses a technique that you may like better, as follows:
<?php
$example = "\n\rSome Kind\r of \nText\n\n";
$replace = array("\r\n", "\n\r", "\r", "\n");
$subs = array("","","","");
$text = str_replace($replace, $subs, $example );
var_dump($text); // "Some Kind of Text"
Live demo here
I doubt that you need "\n\r" but I left it in just in case you feel it is really necessary.
This works by having an array of line termination strings to be replaced with an empty string in each case.
I found the answer is pretty simple. I simply use
$text = $this->storyContent;
$text = str_replace("\\r\\n","<br>",$text);
$text = str_replace("\\n\\r","<br>",$text);
$text = str_replace("\\r","<br>",$text);
$text = str_replace("\\n","<br>",$text);

how do i remove the this "\r\n" in my string

I have problem in sending message to my client via socket,the string that I would like to send is like this "##w32,12345678,xxx,5*zy\r\n"
$msg = $_POST['comm_input']; //"##w32,12345678,xxx,5*zy\r\n"
if this is posted i get the value of $msg which is "##w32,12345678,xxx,5*zy\r\n"
but my client will not accept this kind of message..but if I manually do like this without posting the comm_input;
$testmsg = "##w32,12345678,xxx,5*zy\r\n";
It works fine,I tried to look at in firebug there is no double quotes and \r\n.and it works fine.
if I post the comm_input.and look at in the firebug there is double quotes and \r\n,how can I remove this.
You can use str_replace function to remove \r\n.
DEMO
<?php
$testmsg = "##w32,12345678,xxx,5*zy\r\n"; <-- $_POST value
$order = "\r\n";
$replace = "";
$newstr = str_replace($order, $replace, $testmsg);
echo $newstr; //outputs ##w32,12345678,xxx,5*zy
?>
using str_replace, you need to escape the \ with and extra \, hence, \r as string becomes \\r
$msg = $_POST['comm_input']; //"##w32,12345678,xxx,5*zy\r\n" ;
$new_msg = str_replace("\\r\\n", "", $msg);
Edit: to remove double quotes
$new_msg = str_replace('"', "", $new_msg);
Consider reading this article : Escape Sequence in PHP
you can use
$msg = "##w32,12345678,xxx,5*zy\r\n";
$str = rtrim($msg);
Refer trim() and rtrim()

remove fake comments from json file

since json dosn't support comments I need my own function to clean my comments
My comments are css style, like this
/*comment*/
i tryed the following
$json = preg_replace("/(\/\*.?\*\/)/", "", $json);
but no luck.
thank's
echo preg_replace("#/\*.*?\*/#s", "", $json);
Notable changes:
I used # as the pattern delimiter. By doing this, I don't need to
escape forward slashes, making the regex prettier to read.
I added the s flag, which makes the . also match new line characters.
Beware, this will destroy comments inside a json string. An example json object that will get clobbered
{"codeSample": " /*******THIS WILL GET STRIPPED OUT******/"}
Use the following:
$json = preg_replace('!/\*.*?\*/!s', '', $json); // remove comments
$json = preg_replace('/\n\s*\n/', "\n", $json); // remove empty lines that can create errors
This will erase comments, multi line comments and empty lines
EDIT: as some of the guys were saying in the comments, you can use:
$json = preg_replace('/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/', '', $json);
To remove only comments that are not found within strings.
$string = "some text /*comment goes here*/ some text again /*some comment again*/";
$string = preg_replace( '/\s*(?!<\")\/\*[^\*]+\*\/(?!\")\s*/' , '' , $string );
echo $string; // some textsome text again
The complete php code to remove both single and multi-line comments.
$json = preg_replace('!/\*.*?\*/!s', '', $json); //Strip multi-line comments: '/* comment */'
$json = preg_replace('!//.*!', '', $json); //Strip single-line comments: '// comment'
$json = preg_replace('/\n\s*\n/', "\n", $json); //Remove empty-lines (as clean up for above)
Here a site you can test the code: https://www.phpliveregex.com
To test the first code line fill in like this picture:

Acents become interrogation marks in php when parsing html

i'm getting a PT-BR text automatically from downloading a html page and the acentution becomes interrogation marks when I use uft8_decode, this is my function:
function pegaMsg($string)
{
$bot_url = "http://website.com";
//&rnd=&msg="
$rand_msg = rand(0,100);
$url = $bot_url . $rand_msg . "&msg=" . $string;
$url = str_replace(" ", "%20", $url);
//echo "\n" . $url;
$download = http_get($url, $referer="");
$download['FILE'] = utf8_decode($download['FILE']);
$download['FILE'] = str_replace("var resp = ", "", $download['FILE']);
$download['FILE'] = str_replace("\\r\\n", "", $download['FILE']);
$download['FILE'] = str_replace(";", "", $download['FILE']);
$download['FILE'] = str_replace("\'", "", $download['FILE']);
$download['FILE'] = trim($download['FILE']);
return $download['FILE'];
}
this is the output expected:
VOCÊ TINHA DUAS ESCOLHAS:
and this is what I get:
'VOC? TINHA DUAS ESCOLHAS:
what can I do ? I want the ^ displayed ! thanks and sorry for the bad english
utf8_decode replaces invalid code unit sequences ?. The reason you're getting a ? is likely because the text you're passing to utf8_decode was not in UTF-8 to begin with.
In fact, it's possible it was already in ISO-8859-1, which is the encoding of the string returned by utf8_decode. In that case, your solution would be to just omit the call to utf8_decode.
If the original text was neither in UTF-8 nor in ISO-8859-1 (which is what I'm assuming you want, since you're calling utf8_decode), you have to use iconv or mb_convert_encoding.
A final possibility is that whatever is interpreting the script output is assuming the encoding of the script output is different from what it actually and it also converts invalid code unit sequences to ?.
Try to use encode
$download['FILE'] = utf8_encode($download['FILE']);

Using single 'smart quote' in my JSON data is breaking PHP script

I've got a PHP script that is reading in some JSON data provided by a client. The JSON data provided had a single 'smart quote' in it.
Example:
{
"title" : "Lorem Ipsum’s Dolar"
}
In my script I'm using a small function to get the json data:
public function getJson($url) {
$filePath = $url;
$fh = fopen($filePath, 'r') or die();
$temp = fread($fh, filesize($filePath));
$temp = utf8_encode($temp);
echo $temp . "<br />";
$json = json_decode($temp);
fclose($fh);
return $json;
}
If I utf8 encode the data, when I echo it out I see nothing where the quote should be. If I don't utf8 encode the data, when I echo it out I see the funny question mark symbol �
Any thoughts on how to actually see the proper character??
Thanks!
Is it possibe that the server is sending the json data in an encoding like windows-1252? That codepage has some smart code characters where iso-8859 has control characters. Could you try to use iconv("windows-1252", "utf-8", $temp) instead of utf8_encode. Even better would be if the server already sends utf-8 encoded json, since that is the recommended encoding per rfc4627.
The issue is more on the side, that generates the JSON file. There you should escape the ' by \'
If you can't modify this part, you should do it like this with addslashes:
$temp = fread($fh, filesize($filePath));
$temp = utf8_encode($temp);
echo $temp . "<br />";
$temp = addslashes($temp);
$json = json_decode($temp);
Can you possibly do a string replace assuming the data is all utf8?
$text = str_replace($find, $replace, $text);
Looking for the characters below?
'“' // left side double smart quote
'â€' // right side double smart quote
'‘' // left side single smart quote
'’' // right side single smart quote
'…' // elipsis
'—' // em dash
'–' // en dash

Categories