I'm using str_replace and it's not working correctly.
I have a text area, which input is sent with a form. When the data is received by the server, I want to change the new lines to ",".
$teams = $_GET["teams"];
$teams = str_replace("\n",",",$teams);
echo $teams;
Strangely, I receive the following result
Chelsea
,real
,Barcelona
instead of Chealsea,real,Barcelona.
What's wrong?
To expand on Waage's response, you could use an array to replace both sets of characters
$teams = str_replace(array("\r\n", "\n"),",",$teams);
echo $teams;
This should handle both items properly, as a single \n is valid and would not get caught if you were just replacing \r\n
Try replacing "\r\n" instead of just "\n"
I would trim the text and replace all consecutive CR/LF characters with a comma:
$text = preg_replace('/[\r\n]+/', ',', trim($text))
I had the same issue but found a different answer so thought I would share in case it helps someone.
The problem I had was that I wanted to replace \n with <br/> for printing in HTML. The simple change I had to make was to escape the backslash in str_replace("\n","<br>",($text)) like this:
str_replace("\\n","<br>",($text))
Related
I am trying to remove these \n\n characters that appear in my string when I post a form.
My code is;
$text = $textdb['columnname'];
echo trim(preg_replace('/\s\s+/', ' ', $text));
But it doesn't work. I have tried literally every example here and still nothing works. Am I suppose to do something prior to this? Does this work with a certain version of php? Am using 5.6 by the way. Thanks.
Just use nl2br
Example:
$text = nl2br("hey\n neighbor");
would print
hey
neighbor
Ok, I have a string as follows:
$disallowedBBC = 'abbr|acronym|anchor|bdo|black|blue|br|color|email|flash|font|ftp|glow|green|html|hr|img|iurl|li|list|ltr|url|quote';
And than a preg_replace on the actual string ($message variable) that should get rid of all bbc code that is not allowed according to the $disallowedBBC variable:
$message = preg_replace("/\[($disallowedBBC)[^]]*](.*?)\[\/($disallowedBBC)\]/is", "$2", $message);
But, for some reason, the [hr] tag is getting past this preg_replace. So, in this case:
$message = '[hr]Test';
It outputs the [hr] tag, but should remove it. What is wrong with my regex?
Basically...
How to change it so that it removes all [hr] and/or [hr]Test[/hr] altogether? But would also need to get rid of instances where [url=http://someurl.com]Some Url[/url]. And it should remove [color=red] from a string as follows: [color=red]Testing
For example, it needs to get rid of [{tag}] and if it has a closing tag [/{tag}], but if there is no closing tag, it needs to get rid of the opening tag, and vice versa. It should be able to capture anything within the {tag} that is within the brackets as well, such as: [quote author=Solomon time=7834783470]Just a quote here[/quote] Additional text here...
So, this should output: Just a quote here Additional text here...
I think you need two preg_replaces. One to first get rid of the pairs of [hr]...[/hr] and then a second to get rid of any remaining [hr]...
$message = preg_replace("/\[($disallowedBBC)[^\]]*](.*?)\[\/($disallowedBBC)\]/is", "$2", $message);
$message = preg_replace("/\[($disallowedBBC)[^\]]*]/is", "", $message);
I you try to do it in one step, then things like "abc[br]blahblah[hr]gak[/hr]def" will become "abcdef". You might be able to do it if you can place restrictions on the blahblah portion.
You can, of course, combine these into one preg_replace call by using the array syntax (but remember that the order matters):
$patterns = array("/\[($disallowedBBC)[^\]]*](.*?)\[\/($disallowedBBC)\]/is",
"/\[($disallowedBBC)[^\]]*]/is", );
$replacements = array("$2", "");
$message = preg_replace($patterns, $replacements, $message);
I'm having some weird difficulty with removing "\n"'s from data that is pulled from a database.
The data is an email and gets stored with \n's throughout it by the system that inputs it.
When I display it, I've tried to remove these \n's using the following:
$htmlbody = str_replace("\n", "", $message['htmlbody']);
or
nl2br($message['htmlbody']);
but both commands still return a string that is full of \n's.
The variable $message['htmlbody'] includes a string like \n\n <div>\n Example Data \n </div>\n, and this data remains the same after being passed through str_replace.
The data originally comes from a JSON webhook which has replaced all the newlines in an HTML email with \n's. I have control over the data being put into the database as well, and have tried using the above actions on the original data with the same result.
Any thoughts on what might cause this?
Cheers.
Found this in a google search
$message = preg_replace("/\n|\r/", " ", $message['htmlbody']);
Which will replace newlines with whitespace.
to replace first \r\n then \r and then \n use this:
$message['htmlbody'] = preg_replace(array("/\r\n/", "/\r/", "/\n/"), array(' ',' ', ' '), $message['htmlbody']);
$message['htmlbody'] = str_replace("\n", "", $message['htmlbody']);
If the string you try to modify have \n displayed, and not interpreted as a new line, use :
$message['htmlbody'] = str_replace("\\n", "", $message['htmlbody']);
Try passing $message through stripslashes. It is possible that you have \\n\\r, that is double slashes which prevent correct escaping...
$message['htmlbody'] = nl2br(stripslashes($message['htmlbody']))
I have a jquery editable div that when you click on it you can edit the text. The problem is that when the data is called from the db and placed into the paragraph I keep getting a \n for every space. How can I replace the \n with an actual new line.
I tried nl2br(), but that's not very convenient for my users since they then have to play with the <br /> when they want to edit the paragraph.
Any thoughts?
What about:
str_replace("\\n", "", $str); // see if this gets rid of them
Then this should work to put actual newlines in there:
str_replace("\\n", "\n", $str); // should replace with actual newline
try:-
$strippedText = str_replace(chr(10), '', $textFromDB);
or
$strippedText = str_replace(chr(10), '<br/>', $textFromDB);
Does this work? (Working on the possiblity that the newlines are already escaped).
$strippedText = str_replace('\\n', ' ', $textFromDB);
Are you using a ready made solution or making your own? I use http://aloha-editor.org/ for stuff like this and it's mostly problem free.
Have you tried str_replace?
$myTextFromDB = str_replace('\n', PHP_EOL, $myTextFromDB);
Ok, I think this is different enough that I should do a separate answer for it.
Are you saying a literal "slash n" shows up on the page? Or are you saying that your newlines show up as spaces?
If it's the latter, then there's no way around that. HTML will show newlines only as a space - you have to convert to br tags to break the line if it's not in a textarea context. But you can always convert them back to newlines when you pop that textarea up for your user and this should work well for people.
I can't get nl2br function to work after fetching data from my database:
$result = mysql_query("SELECT comments..etc.etc..");
while ($row = mysql_fetch_array($result))
{
echo nl2br($row["comments"]);
}
In database row comments:
\r\nThanks,\r\n
OUTPUT:
Same as in DB:
\r\nThanks,\r\n
If I simply test this out like so it works fine:
<?php
$mystring = "\r\nThanks,\r\n";
echo nl2br($mystring);
?>
OUTPUT:
converts \r \n to <br />
try this:
echo preg_replace('/\v+|\\\r\\\n/Ui','<br/>',$row["comments"]);
I know this is an old post but if like me you are have stumbled across this issue and the above didn't work for you, this solution may help you instead:
echo nl2br(stripslashes($row["comments"]));
or (they are not the same function, note the additional "c" after strip)
echo nl2br(stripcslashes($row["comments"]));
See original thread that helped me: nl2br() not working when displaying SQL results
Most likely you are doing escaping twice, when adding your data into DB.
Check your code that adds data to DB and remove unnecessary escaping.
Most likely it's some senseless "universal sanitization" function.
Well it's easy.
Let's take a quote, not a newline to demonstrate. The behavior the same.
Slashes being stripped then data goes to database.
Thus, in the normal case:
source: It's
after escaping: It\'s
by the query execution slash being stripped and
both in the database and back It's
in double escaping case:
source: It's
after escaping: It\'s
after second escaping: It\\\'s
by the query execution slash being stripped and
both in the database and back It\'s
we have our data spoiled.
Just make yourself understand that escaping i not something magical that makes your data "safe" (and, therefore can be done many times, as you probably think). It's just adding a backslash to certain symbols.
My guess is that the slashes in your DB are literal slashes (followed by n or r), not newlines. Can you find a way to store literal newlines in your database?
Following solution will work for both windows as well as for linux/unix machine
str_replace(array("\\r\\n", "\\r", "\\n"), "<br />", "string");
Make sure that you are not to using strings from file and/or set in single apostrophe. Because string is treated literally, and nl2br will not work.
NL2BR will work with double apostrophe.
Building on what Christian is saying, why don't you trying replacing the literal '\r\n' with "\r\n"?
Data you have stored is allready added the slashes.
You have to use stripslashes() first then str_replace()
stripslashes(str_replace('\r\n','<br/>',$row["comments"]))
For some reason this didn't work for me...
echo nl2br(stripcslashes($row["comments"]));
But this did...
$comments = stripcslashes($row["comments"]);
$commentsWithBreaks = nl2br($comments);
echo $commentsWithBreaks;
Not working for me either. I just did the following:
$mensaje = str_replace("
", "<br/>", $mensaje);
I was able to replace newline with <br> using this code :
str_replace(array("\r\n", "\r", "\n"), "<br>", "input");
(windows machine)
This could be a solution, at least it was for me.
$message = str_replace("\\r\\n", "<br>", $message);
It is possible that you are getting a string in which the slashes are escaped (i.e. \\) and nl2br works with \n\r not \\n\\r
Once you understand this, the solution is easy :)