我想在某些条件下使用str_replace。
我正在开发一个应用程序,它从文本区域输入一个文本块并将其输出为1行。每当" end of line
"或" space + with end of line
&#34;如果符合,则字符串将替换为<br>
我现在已经找到了解决方案,即只要满足end of line
,字符串就会被<br>
替换。但是,如果用户在space
之前键入end of line
,我需要在用<br>
替换EOL之前删除该空格。
我的代码
$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
输出我的代码
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
必需的输出
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>
完整代码
<?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>
<START><br>
<TITLE><?php echo $title; ?></TITLE><br>
<BODY><br>
<P><?php echo $page; ?></P><br>
<P><?php echo $refresheddata; ?></P><br>
</BODY><br>
<END>
</body>
</html>
答案 0 :(得分:5)
简单的方法,只需更换两者:
$refresheddata = str_replace([" \n","\n"], '<br>', $data);
也可以使用简单的正则表达式完成,例如
$refresheddata = preg_replace("/ ?\n/",'<br>',$data);
正则表达式解决方案可能更通用,因为它也可以更新以处理稍微不同的其他情况,例如同时在换行符之前的多个空格。根据您的需求选择,以及如何更好地维护代码。
答案 1 :(得分:1)
最后我得到了答案。由于我使用textarea作为输入,所有其他答案都是错误的,我仍然在EOL获得空间。 我尝试替换我的str_replace函数参数并获得所需的输出。
解
$refresheddata = str_replace(array(" \r\n","\r\n"), '<br>', $data);
现在新线路已经消失了。