将 <br /> 转换为新行以在文本区域使用


Converting <br /> into a new line for use in a text area

如果我有一个变量:

$var1 = "Line 1 info blah blah <br /> Line 2 info blah blah";

还有一个文本区域:

<textarea>echo $var1</textarea>

如何让文本区域显示新行,而不是在带有<br />的单个 like 上显示文本?

编辑:我尝试了以下方法:

<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>

但是,文本区域仍包含行中的br标记。

试试这个

<?php
    $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><?php echo $text; ?></textarea>

我使用以下构造来转换回 nl2br

function br2nl( $input ) {
    return preg_replace('/<br's?'/?>/ius', "'n", str_replace("'n","",str_replace("'r","", htmlspecialchars_decode($input))));
}

在这里,我替换了'n'r符号$input因为 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();

结果:

1.1471637010574E-6 sec/function one (preg_replace)
1.6027762889862E-6 sec/function two (str_ireplace)

这是另一种方法。

class orbisius_custom_string {
    /**
     * The reverse of nl2br. Handles <br/> <br/> <br />
     * usage: orbisius_custom_string::br2nl('Your buffer goes here ...');
     * @param str $buff
     * @return str
     * @author Slavi Marinov | http://orbisius.com
     */
    public static function br2nl($buff = '') {
        $buff = preg_replace('#<br[/'s]*>#si', "'n", $buff);
        $buff = trim($buff);
        return $buff;
    }
}

编辑:之前的答案是你想要的倒退。 使用str_replace。将<br>替换为'

echo str_replace('<br>', "'n", $var1);
<?php
$var1 = "Line 1 info blah blah <br /> Line 2 info blah blah";
$var1 = str_replace("<br />", "'n", $var1);
?>
<textarea><?php echo $var1; ?></textarea>