I need to trim any trailing \n from strings.
I used rtrim but for some reason it's not working. The string remains the same with or without rtrim. It's driving me crazy.
This is the code:
$strippedDescription = rtrim($strippedDescription);
where $strippedDescription is:
The owner of Hill House is Scott Croyle, senior vice president of design at HTC. At two bedrooms, 2 1/2 baths and a study, the home is just large enough to share with his wife and son. Its modest scale allowed Bernstein to emphasize quality materials over quantity of space.
"It's almost a negative value in that (tech) community," said Bernstein of over-the-top homes. "There's a real emphasis on not seeking a mansion right away."\n\n
EDIT
Ok so the issue is that $strippedDescription is being read from an RSS feed and stored in our database. It's the article content. This content will later be displayed on an iPhone thru an app.
The iphone programmer said that we need to replace the "< b r / >" and "< / p>" with "\n" so the iphone will correctly recognize the new line. However this isn't happening. The \n are displayed as part of the article.
This is the code preceding the above part (where $itemDescription is the article content with all html tags):
$strippedDescription = $itemDescription;
$strippedDescription = str_replace('</p>', '\n', $itemDescription);
$strippedDescription = str_replace('<br/>', '\n', $itemDescription);
$strippedDescription = str_replace('<br />', '\n', $itemDescription);
$strippedDescription = strip_tags($strippedDescription);
$strippedDescription = rtrim($strippedDescription);
EDIT
Ok I replaced the '\n' with "\n" (double quotes) and that seems to have solved the problem.
Thank you Alex and Sergi and the rest for pointing me in the right direction.
It looks like you have the literal characters \n at the end. trim() won't remove these, as they're not whitespace.
Looks like something like this would work...
$str = preg_replace('/(\\\n)+\z/', '', $str);
CodePad.
We've several problems here.
The \n is NOT a single character, as the rtrim is not working.
However, you've to search for a STRING and not a single character. Thats why double quotes should be used while searching the \n.
The second problem, is that as you can see in the question, there are two \n at the end, and might there be more.
What I'd do, is manually program a function that does the following:
Reverse the string
Loop while 2 first characters == "n\".
Replace those two characters for a blank.
End loop
Related
I have developed a simple PHP feed system which displays all of the logged in users posts. It works fine, however, I have come across a "bug" where if the user has made a status which contains leading and/or trailing <br> points, it'll break the status view.
Now, before anyone marks this as a duplicate; If have tried the following approaches (and two more from posts which I can no longer find) in removing the trailing and leading <br>'s:
Remove <br>'s from the end of a string
How to trim all leading/trailing code using php
However, they a) do nothing at all, or b) do work, but remove all the <br> points within the string, even if they are in the middle.
Attempts:
$ctx = preg_replace('/^(<br>){0,}|(<br>){0,}$/m', '', nl2br(escape($post->ctx)));
$ctx = preg_replace('/(<br>)+$/', '', nl2br(escape($post->ctx)));
$ctx = preg_replace('#(( ){0,}<br( {0,})(/{0,1})>){1,}$#i', '', nl2br(escape($post->ctx)));
I have been working on this for a little while now, but have come up with no proper fix. I have come close with attempt c, however, it would remove all <br> points.
All help is appreciated,
Thanks!
Try to replace with contents optionally wrapped by the <br />'s (note that nl2br inserts <br />):
^(?:<br />[\n\r]+)*(.*?)(?:<br />[\n\r]+)*$
Demo: https://regex101.com/r/7KDCuA/3
And the PHP code:
$input = "\nHello World\nhello world\n\n";
$unwrapped = preg_replace("|^(?:<br />[\n\r]+)*(.*?)(?:<br />[\n\r]+)*$|s", '$1', nl2br($input));
echo $unwrapped;
Demo: http://codepad.org/BT0A5583
sounds to me like this should already help:
nl2br(escape(trim($post->ctx)));
This will work, if the users aren't allowed to enter html for their status. The trim will remove all whitespaces at the beginning and the end of the string and so the string passed to nl2br has no line breaks at the beginning and at the end.
I have a string I want to process which looks like this:
HHHHHHHHHHHHHHGGGHHHHHHHHHHHHHHH GGGGGG TTTTT SHHHHHH HHHHHHHHHHHHHHHH
Note how there are multiple spaces between characters. The number of spaces is important, and thus I don't want them to be discarded. When I read this line from a file using php, it prints the following:
HHHHHHHHHHHHHHGGGHHHHHHHHHHHHHHH GGGGGG TTTTT SHHHHHH HHHHHHHHHHHHHHHH
Maintaining only a single space where there were several before. How can I stop PHP from doing this?
Ultimately I want to substring the entire thing into an array of individual characters but I need the array position to be preserved.
Thank you!
EDIT: Example of what I'm talking about:
Replace it with the html entity for a non breaking space to view it rendered in browser's html
<?php
$str = ' HHHHHHHHHHHHHHGGGHHHHHHHHHHHHHHH GGGGGG TTTTT SHHHHHH HHHHHHHHHHHHHHHH';
$str = str_replace(' ',' ',$str);
echo $str;
If you're viewing it with a browser you could use HTML to keep the formatting intact. For instance:
echo '<pre> HHHHHHHHHHHHHHGGGHHHHHHHHHHHHHHH GGGGGG TTTTT SHHHHHH HHHHHHHHHHHHHHHH</pre>';
See: http://www.w3schools.com/tags/tag_pre.asp
I think <code> might also work.
I have searched throughout this site and google, and could not find a viable solution. There are solutions, but none seem to work for me.
I have a text area that serves as the input for a form, as well as the output (editable) when displaying the form to edit. So, I have a textarea like so:
echo '<textarea>'.$resolution.'</textarea>';
If I enter something with line breaks, it is interpreted as \r\n wherever there is a carriage return. Example:
Input:
This is a
test.
Output:
This is a\\r\\n\\r\\ntest.
Now, I found it simple to remove the extra slash by using stripslashes as follows:
$resolution = stripslashes($resolution);
...but, now the output is:
This is a\r\n\r\ntest.
I cannot figure out how to convert \r\n to a line break (that is, without using a tag, since that would only output <br> within the textarea, where html would not be supported. I've tried all of the following, but none of them worked:
//Effort 1
$resolution = trim($resolution);
//Effort 2
$resolution = nl2br($resolution);
//Effort 3
$resolution = htmlentities($resolution);
//Effort 4
$resolution = preg_replace("\\r\\n","<br>",$resolution);
I'm now at a complete loss. Can anyone shed some light on this?
PHP has two different string building modes. The first uses single quotes, and will do absolutely no variable or special character substitutions. That's what you're using.
The second is variable-embedding in double quoted strings, which should work:
$text = str_replace("\\", "\", $text);
echo "<textarea>$text</textarea>";
The \r and \n should now be active carriage return and newline characters in your output, not the character "slash" and then an 'r' or 'n'
Just use double quotes on str_replace
str_replace('\r',"\r",str_replace('\n',"\n",$resolution));
http://php.net/manual/en/language.types.string.php
or if you're really dealing with double backslashes:
str_replace('\\\\r',"\r",str_replace('\\\\n',"\n",$resolution));
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'm pulling articles from specific URLs for conversion to sentences, but the text body has a random behavior of eliminating whitespace between some sentences resulting in:
Jane went to the store.She bought a dog. The dog was very friendly.It had no teeth.
Some of my text is stock symbols (AZ.GAN) etc. So I can't simply insert a space between all periods which have no adjacent whitespace.
Jane bought several shares of (TY.JPN). She lost all her cash money."Arg!" She cried.
The above example would destroy the stock symbol variable.
Curious if anyone knows the cause of this. I have tried several HTML and DOM. I use Simple_DOM to grab the plaintext. Although, I get the same result if I do it manually, or with any other parsing engine.
Unfortunately I don't have an approach for your specific question, but is it possible that the missing space between sentences is actually a linebreak (e.g. \n) that your text viewer (whatever it is) isn't showing you?
Perhaps try something like this just to make sure
var articleContent = ... // get content
articleContent = articleContent.replace(/\n/g, ' NEW LINE ');
Try doing:
$str = trim(preg_replace('~([(].+?[.])\s(.+?[)])~', '$1$2', str_replace('.', '. ', $str)));