Nick S
Nick S

Reputation: 1

PHP rtrim not removing trailing \n

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.

Upvotes: 0

Views: 1045

Answers (2)

Reinherd
Reinherd

Reputation: 5504

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:

  1. Reverse the string
  2. Loop while 2 first characters == "n\".
  3. Replace those two characters for a blank.
  4. End loop

Upvotes: 0

alex
alex

Reputation: 490657

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.

Upvotes: 2

Related Questions