views:

111

answers:

5

Is there stock standard function that does newline to <br /> encoding in ASP.Net MVC?

+2  A: 
mystring.Replace("\r\n","<br />");
David
+2  A: 

I don't believe there's a 'stock standard function' to do this exactly the same as PHP's nl2br() function however the following will do the equivelant:

myString.Replace("\r\n", "<br />");
Jamie Dixon
If one is very strict, this method call is clearly not "exactly the same" as phps nl2br. For a more detailed specification of what nl2br actually does, see: http://us3.php.net/nl2br - and thats not just for this answer, but for most of the answers so far.
Max
The question asks 'is there somethig like...' which is different from 'is there something exactly the same'. This solution is 'something like'.
Jamie Dixon
+2  A: 

There is now:

public static class StockStandardFunctions
{
    public static string Nl2br(this string input)
    {
        return input.Nl2br(true);
    }

    public static string Nl2br(this string input, bool is_xhtml)
    {
        return input.Replace("\r\n", is_xhtml ? "<br />\r\n" : "<br>\r\n");
    }
}

Amended to follow the php spec for nl2br a little more closely (thanks Max for pointing that out). This still assumes \r\n new lines though...

Daniel Renshaw
It was my impression that nl2br was a lot more robust than this. I could be wrong, though.
Dan Tao
@Daniel: You spelled Standard wrong ;)
My Other Me
@myotherme: wish I could say that was intentional! (fixed)
Daniel Renshaw
+2  A: 

All these answers are quite correct, but you should do a mystring.Replace("\r?\n", "<br />"); to catch UNIX line endings as well, if your source (user input or db) might deliver that.

Residuum
+1  A: 

What about something along the lines of:

public static string Nl2br(string str)
{
    return Nl2br(str, true);
}

public static string Nl2br(string str, bool isXHTML)
{
    string brTag = "<br>";
    if (isXHTML) {
        brTag = "<br />";
    }
    return str.Replace("\r\n", brTag + "\r\n");
}

Here's the function signature from the PHP documention:

string nl2br ( string $string [, bool $is_xhtml = true ] )

The PHP function also appends a newline after the break tag.

webbiedave