如果我有一个变量:
$var1 = "Line 1 info blah blah <br /> Line 2 info blah blah";
Run Code Online (Sandbox Code Playgroud)
和文字区域:
<textarea>echo $var1</textarea>
Run Code Online (Sandbox Code Playgroud)
如何让文本区域显示一个新行,而不是将文本显示在单个文本区域<br />中?
编辑:我尝试了以下内容:
<textarea class="hobbieTalk" id="hobbieTalk" name="hobbieTalk" cols="35" rows="5" onchange="contentHandler('userInterests',this.id,this.value,0)"><?php
$convert=$_SESSION["hobbieTalk"];
$convert = str_replace("<br />", "\n", $convert);
echo $convert;
?></textarea>
Run Code Online (Sandbox Code Playgroud)
但是文本区域仍然包含br行中的标记.
Mob*_*dde 79
试试这个吧
<?
$text = "Hello <br /> Hello again <br> Hello again again <br/> Goodbye <BR>";
$breaks = array("<br />","<br>","<br/>");
$text = str_ireplace($breaks, "\r\n", $text);
?>
<textarea><? echo $text; ?></textarea>
Run Code Online (Sandbox Code Playgroud)
aft*_*4ik 15
我使用以下构造转换回nl2br
function br2nl( $input ) {
return preg_replace('/<br\s?\/?>/ius', "\n", str_replace("\n","",str_replace("\r","", htmlspecialchars_decode($input))));
}
Run Code Online (Sandbox Code Playgroud)
在这里,我更换\n并\r从$输入符号,因为nl2br这么想的删除它们,这会导致错误的输出,\n\n或\r<br>.
@Mobilpadde 的回答很好。但这是我使用preg_replace的正则表达式解决方案,根据我的测试,它可能会更快。
echo preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");
function function_one() {
preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");
}
function function_two() {
str_ireplace(['<br />','<br>','<br/>'], "\r\n", "testing<br/><br /><BR><br>");
}
function benchmark() {
$count = 10000000;
$before = microtime(true);
for ($i=0 ; $i<$count; $i++) {
function_one();
}
$after = microtime(true);
echo ($after-$before)/$i . " sec/function one\n";
$before = microtime(true);
for ($i=0 ; $i<$count; $i++) {
function_two();
}
$after = microtime(true);
echo ($after-$before)/$i . " sec/function two\n";
}
benchmark();
Run Code Online (Sandbox Code Playgroud)
结果:
1.1471637010574E-6 sec/function one (preg_replace)
1.6027762889862E-6 sec/function two (str_ireplace)
Run Code Online (Sandbox Code Playgroud)