如何在条件中使用str_replace

Din*_*ino 2 html php str-replace

我想在某些条件下使用str_replace.我正在开发一个应用程序,它从文本区域输入一个文本块并将其输出为1行.只要满足" end of line"或" space + with end of line",字符串就会替换为<br>

我现在已经找到了解决方案,无论何时end of line满足,字符串都被替换为<br>.但是如果用户输入一个space之前end of line,我需要在更换EOL之前摆脱那个空间<br>.

我的代码

$refresheddata = str_replace("\n", '<br>', $data);
Run Code Online (Sandbox Code Playgroud)

样本输入

This is the first line with a space at the end 
This is the second line which donot have a space at the end
Run Code Online (Sandbox Code Playgroud)

输出我的代码

This is the first line with a space at the end <br>This is the second line which donot have a space at the end
Run Code Online (Sandbox Code Playgroud)

需要的输出

This is the first line with a space at the end<br>This is the second line which donot have a space at the end
Run Code Online (Sandbox Code Playgroud)

检查之前的空间 <br>

完整的代码

<?php 
$page = $data = $title =  $refresheddata = '';
if($_POST){
    $page = $_POST['page'];
    $data = $_POST['data'];
    $title = $_POST['title'];
    $refresheddata = str_replace("\n", '<br>', $data);
    $refresheddata = htmlentities($refresheddata);
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Data</title>
</head>
<body>
<form method="post">
    <h3>Original Text</h3>
    <input type="text" name="title" placeholder="Enter your title here.." style="font-size:16px; padding:10px;" required><br><br>
    <input type="text" name="page" placeholder="Enter your page data here.." style="font-size:16px; padding:10px;" required><br><br>
    <textarea name="data" rows="15" style="width:100%" placeholder="Enter your remaining contents here..." required></textarea>
    <input type="submit">
</form><br><br>

<h3>Result Text</h3>
&lt;START&gt;<br>
&lt;TITLE&gt;<?php echo $title; ?>&lt;/TITLE&gt;<br>
&lt;BODY&gt;<br>
&lt;P&gt;<?php echo $page; ?>&lt;/P&gt;<br>
&lt;P&gt;<?php echo $refresheddata; ?>&lt;/P&gt;<br>
&lt;/BODY&gt;<br>
&lt;END&gt;
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Cal*_*ero 5

简单的方法,只需更换两个:

$refresheddata = str_replace([" \n","\n"], '<br>', $data);
Run Code Online (Sandbox Code Playgroud)

它也可以通过简单的正则表达式来完成,就像这个一样

$refresheddata = preg_replace("/ ?\n/",'<br>',$data);
Run Code Online (Sandbox Code Playgroud)

正则表达式解决方案可能更通用,因为它也可以更新以处理稍微不同的其他情况,例如同时在换行符之前的多个空格.根据您的需求选择,以及如何更好地维护代码.