如何在条件下使用 str_replace

How to use str_replace with a condition

我想在某些条件下使用 str_replace。 我正在开发一个应用程序,它从文本区域输入一段文本并将其输出为 1 行。每当遇到“end of line”或“space + with end of line”时,字符串就会被替换为 <br>

我现在有了解决方案,每当满足 end of line 时,字符串就会被 <br> 替换。但是如果用户在 end of line 之前键入 space ,我也需要在用 <br>.

替换 EOL 之前摆脱那个 space

MY CODE

$refresheddata = str_replace("\n", '<br>', $data);

SAMPLE INPUT

This is the first line with a space at the end 
This is the second line which donot have a space at the end

OUTPUT OF MY CODE

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

REQUIRED OUTPUT

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

勾选<br>

前的space

FULL CODE

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

最简单的方法,只需替换两者即可:

$refresheddata = str_replace([" \n","\n"], '<br>', $data);

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

$refresheddata = preg_replace("/ ?\n/",'<br>',$data);

正则表达式解决方案可能更通用,因为它也可以更新以处理略有不同的其他情况,例如多个 space 同时在换行符前面。根据您的需要以及如何更好地维护代码来选择。

终于找到答案了。由于我使用 textarea 作为输入,所有其他答案都是错误的,我仍然在 EOL 得到 space。 我尝试替换我的 str_replace 函数参数并获得所需的输出。

SOLUTION

$refresheddata = str_replace(array(" \r\n","\r\n"), '<br>', $data);

现在新行和它前面的 space 一起消失了。