I want to replace linebreaks with ' ' in PHP. Somehow I can't get it to work on this json encoded string [[0,"Hello World"],[1,"s\n"]] with $x = preg_replace('/\r\n|\r|\n\r|\n/m', ' ', $x);.
I'm out of ideas. And i know that the php code works with none-json encoded strings. Any ideas to fix this problem
Forgot this:
When I input the string as $xthe function or php code returns the same string. Instead of replacing \n with ' '.
I have also tried all relevant problems in Stackoverflow. none of them successful
preg_replace will try to parse the '\n' as an actual newline character, so you need some more escaping in there.
$x = preg_replace('/\\\r\\\n|\\\r|\\\n\\\r|\\\n/m', ' ', $x);
This is all kind of ugly though. Is there a reason you can't do a replace in the actual decoded strings instead?
Related
I have a textarea in my html for user to input some text. I can get it to save into mysql table field with text attribute using php. Before insert into mysql, I will mysql_real_escape_string($data);(for security reason). But when I retrieve it back out from database, I will get
{"bittext":"i
love
mcD"}
With that I will get error:
Error: JSON Parse error: Unterminated string
parse#[native code]
I am not sure how I can reformat it back so that I can parse it to JSON.
Update:
I found out that I did not add json_encode($data) function. Now I can turn
{"bittext":"i
love
mcD"}
into
{"bittext":"i\nlove\nmcD"}
But I am having problem to convert \n to \\n using $data = str_replace(array('\r\n', '\r', '\n'),'\\n', $data);. For some reason \\n is not working. Is there other way to do this?
Update2:
After much of messing around with the code, I finally got it to work:
$je = json_encode($rs,JSON_PRETTY_PRINT);
$nl = array('\r\n', '\r', '\n');
$je = str_replace($nl,'\\n', $je);
My initial issue is when I log it with firephpcore, I can only see \n even after str_replace($nl,'\\n', $je). But as I do more test and found out it actually already work even though it did not display well in console.
From the documentation for mysql_real_escape_string();
mysql_real_escape_string() calls MySQL's library function
mysql_real_escape_string, which prepends backslashes to the following
characters: \x00, \n, \r, \, ', " and \x1a.
Your insert statement will inculde the string '{"bittext":"i \\nlove \\nmcD"}' - notice we are escaping the escape character here, which is what mysql_real_escape_string() does.
Which will insert into your table the string '{"bittext":"i \nlove \nmcD"}' - this is what you should see if you do a select from the mysql client.
Somewhere, either pre-insert, or post-select your code is processing the value and changing '\n', to an actual newline byte, instead of leaving it as the string '\n'.
You could patch this by running;
$data = str_replace(array("\r\n", "\r", "\n"), "\\n", $data);
However, I would recommend you track back through your code to see where in your pipeline escaped strings are getting converted to actuals.
so I have a string that goes like this:
$string = "This is a test string. It has characters like these: '";
Is there a php function that transforms these to their correspondent character, in my example the desired output would be:
print $string
// OUTPUT: This is a test string. It has characters like these: '
yes there is:
htmlspecialchars_decode($string, ENT_QUOTES);
not sure about the specific ' char, as far as I know htmlspecialchars (with ENT_QUOTES flag) convert an apostrophe (') to ' (with a leading zero)
so the exact behavior on ' worth checking
EDIT:
I made the test and it does work :)
You can use html_entity_decode()
It's like reverse htmlentities. If you use quotes in your input string you have to set the second parameter of html_entity_decode() to ENT_QUOTES
See it in action: http://sandbox.onlinephpfunctions.com/code/7f4649eb47a8e639c514787a100b63bbad4bc8c6
I'm working on transferring data from one database to another. For this I have to map some values (string) to integers and this is where I run into a strange problem.
The string looks like this $string = "word anotherword"; so two words (or one space).
When I explode the string or count the amount of spaces it misses the white space. Why? I var_dumped the variable and it says it's a string.
Below is the code i'm using.
echo "<strong>Phases</strong>: ".$fases = mapPhase($lijst[DB_PREFIX.'projectPhase']);
The string that's being send to the function is for example "Design Concept". This calls the following function (where the spaces get ignored)
function mapPhase($phases){
echo "Whitespace amount: ".substr_count($phases, ' ')."<br />";
}
For the example string given this function echoes 0. What's causing this and how can i fix it? The strangest thing is that for one instance the function worked perfectly.
More than one whitespaces (in HTML) are always converter into one whitespace. For example code indents.
If you want to print more than one, one by one use &nbps; instead.
function mapPhase($phases){
echo 'Whitespace amount: '.substr_count($phases, ' ').'<br />';
}
It may well be that the alleged space in the string may not be a space as in ' ', but something similar, which gets rendered in the browser in the same way as ' ' would. (for a rudimentary list of possible characters: http://php.net/manual/en/function.trim.php)
Thus, checking what the whitespace exactly is may be the solution to that problem.
Maybe they are not even spaces. Try ord() for each symbol in your string.
ord(' ') is 32.
You can use:
$string = preg_replace('/\s+/', '', $string);
I've tried about everything to delete some extra \n characters in a web application I'm working with. I was hoping someone has encountered this issue before and knows what can be causing this. All my JS and PHP files are UTF-8 encoded with no BOM.
And yes I've tried things like
In JS:
text.replace(/\n/g,"")
In PHP:
preg_replace("[\n]","",$result);
str_replace("\n","",$result);
and when I try
text.replace(/\n/g,"")
in the firebug console using the same string I get from the server it works but for reason it doesn't work in a JS file.
I'm desperate, picky and this is killing me. Any input is appreciated.
EDIT:
If it helps, I know how to use the replace functions above. I'm able to replace any other string or pattern except \n for some reason.
Answer Explanation:
Some people do and use what works because it just works. If you are like me and for the record I always like to know why what works WORKS!
In my case:
Why this works? str_replace('\n', '', $result)
And this doesn't? str_replace("\n", '', $result)
Looks identical right?
Well it seems that when you enclose a string with a character value like \n in double quotes "\n" it's seen as it's character value NOT as a string. On the other hand if you enclose it in single quotes '\n' it's really seen as the string \n. At least that is what i concluded in my 3 hours headache.
If what I concluded is a setup specific issue OR is erroneous please do let me know or edit.
In php, use str_replace(array('\r','\n'), '', $string).
I guess the problem is you also have \r's in your code (carriage returns, also displayed as newlines).
In javascript, the .replace() method doesn't modify the string. It returns a new modified string, so you need to reference the result.
text = text.replace(/\n/g,"")
Both of the PHP functions you tried return the altered string, they do not alter their arguments:
$result = preg_replace("[\n]","",$result);
$result = str_replace("\n","",$result);
Strangely, using
str_replace(array('\r','\n'), '', $string)
didn't work for me. I can't really work out why either.
In my situation I needed to take output from the a WordPress custom meta field, and then I was placing that formatted as HTML in a javascript array for later use as info windows in a Google Maps instance on my site.
If I did the following:
$stockist_address = $stockist_post_custom['stockist_address'][0];
$stockist_address = apply_filters( 'the_content', $stockist_address);
$stockist_sites_html .= str_replace(array('\r','\n'), '', $stockist_address);
This did not give me a string with the html on a single line. This therefore threw an error on Google Maps.
What I needed to do instead was:
$stockist_address = $stockist_post_custom['stockist_address'][0];
$stockist_address = apply_filters( 'the_content', $stockist_address);
$stockist_sites_html .= trim( preg_replace( '/\s+/', ' ', $stockist_address ) );
This worked like a charm for me.
I believe that usage of \s in regular expressions tabs, line breaks and carriage returns.
I have a huge text that i keep getting in a json format. When i receive them in json, for some special characters like ' " ©, i receive them differently. i am using php and json to convert json into html. for example, i receive
' as \c101d (single quote)
" as \c201d (opening quote)
" as \c202d (closing quote)
I am planning to keep all the ', " into an array and use that array to replace the \c101d values in the text to ' or something like that so that it is easier to check the whole text in one command, replace all the special characters properly and display them correctly on my webpage.
Maybe some like $arr=array("\c101d"=>"'", "\c202d"=>""") and then call this array on the $text variable to check for characters similar to that in the array and do a string replace.
I have the idea but coding-wise how do i achieve this? Appreciate any help.
SOLVED
Well this piece of code solved all the problems, including ' , " , and all other weird characters.
$newtext=mb_convert_encoding($text, 'HTML-ENTITIES','UTF-8');
¿Are you using json_encode() with the different option flags?
For the substring replacement you should use strtr()
str_replace should do what you want.
This function returns a string or an array with all occurrences of search in subject replaced with the given replace value.
The str_replace function takes arrays as possible parameters for search and replace, so you could do something like:
$search = array( '\'' , '"', ...);
$replace = array( '\c101d', '\c201d', ...);
$text = str_replace($search, $replace, $text);