javascript 变量字符串内的换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9645396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Newline inside variable string
提问by Christian Eric Paran
What if I have a long input of string? maybe 50-250 characters. and I echoed the variable it would echo a very long line of letters and words.
如果我输入很长的字符串怎么办?也许 50-250 个字符。我回显了变量,它会回显很长的字母和单词行。
So, how will I let the variable auto Newline itself? maybe after 50 characters it would new line when echoed.
那么,我将如何让变量自动换行?也许在 50 个字符后,它会在回显时换行。
I have thought of counting the length of the string and looping it and after counting 50 characters it would Newline but if i do that it would slow down the Site.
我想过计算字符串的长度并循环它,在计算 50 个字符后它会换行,但如果我这样做,它会减慢站点的速度。
is there any function to Newline a VARIABLE STRING
? or i should use Looping instead?
换行 a 有什么功能VARIABLE STRING
吗?或者我应该改用循环?
采纳答案by Guillaume Poussel
You can use a built-in PHP function: wordwrap
.
您可以使用内置的 PHP 函数:wordwrap
.
If you want to cut at 50 characters and insert a HTML line-break:
wordrap($str, 50, "<br />");
You can also use the last parameter to force return, even if the string does not contain spaces.
如果要截取 50 个字符并插入 HTML 换行符:
wordrap($str, 50, "<br />");
也可以使用最后一个参数强制返回,即使字符串不包含空格。
回答by Joakim Johansson
You can insert escape characters into a string, such as \n
which will be translated to a new line break.
您可以在字符串中插入转义字符,例如\n
将其转换为换行符。
回答by Ibrahim Azhar Armar
You can use PHP_EOL
in conjunction with strlen()
to acheive what you want.
你可以PHP_EOL
结合使用strlen()
来达到你想要的效果。
回答by Zunair
Just adding more info about \n
:
只需添加有关以下内容的更多信息\n
:
// PHP 5.5.12
// This works for outputing to browser:
$XmlHeader = '<?mso-application progid="Excel.Sheet"?>' . "\n";
// These do NOT work:
$XmlHeader = '<?mso-application progid="Excel.Sheet"?>' . '\n';
$XmlHeader = '<?mso-application progid="Excel.Sheet"?>\n';
回答by ab_dev86
If you can manage the string in php i think the definitive solution is using function wordwrap: http://www.php.net/manual/en/function.wordwrap.php
如果您可以在 php 中管理字符串,我认为最终的解决方案是使用函数 wordwrap:http://www.php.net/manual/en/function.wordwrap.php
You can set the max lenght of a row, the braek parameter (in your case /n).
您可以设置一行的最大长度,即 braek 参数(在您的情况下为 /n)。
The function returns a string with the /n breaks and you can print it.
该函数返回一个带有 /n 中断的字符串,您可以打印它。