Is there stock standard function that does newline to <br />
encoding in ASP.Net MVC?
views:
111answers:
5
+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
2010-04-29 14:40:27
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
2010-04-29 14:48:51
The question asks 'is there somethig like...' which is different from 'is there something exactly the same'. This solution is 'something like'.
Jamie Dixon
2010-04-29 14:54:12
+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
2010-04-29 14:42:30
It was my impression that nl2br was a lot more robust than this. I could be wrong, though.
Dan Tao
2010-04-29 15:08:58
+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
2010-04-29 14:45:08
+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
2010-04-29 15:07:01