我想在某些条件下使用 str_replace。
我正在开发一个应用程序,它从文本区域输入一段文本并将其输出为 1 行。每当遇到“end of line
”或“space + with end of line
”时,字符串将被替换为 <br>
我现在有了解决方案,无论何时end of line
满足,字符串被替换为 <br>
.但是如果用户键入 space
之前 end of line
,在用 <br>
替换 EOL 之前,我也需要摆脱那个空间.
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>
之前的空格
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>
<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>
最佳答案
简单的方法,只需替换两者:
$refresheddata = str_replace([" \n","\n"], '<br>', $data);
也可以用一个简单的正则表达式来完成,就像这个
$refresheddata = preg_replace("/ ?\n/",'<br>',$data);
正则表达式解决方案可能更通用,因为它也可以更新以处理略有不同的其他情况,例如同时在换行符前有一个以上的空格。根据您的需要以及如何更好地维护代码进行选择。
关于php - 如何在条件下使用 str_replace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46618785/