【发布时间】:2018-03-19 00:43:31
【问题描述】:
我想在某些条件下使用 str_replace。
我正在开发一个应用程序,它从文本区域输入一块文本并将其输出为 1 行。每当遇到“end of line”或“space + with end of line”时,字符串就会被<br>替换
我现在提供的解决方案是,只要遇到end of line,字符串就会被<br> 替换。但是,如果用户在 end of line 之前键入 space ,我也需要在用 <br> 替换 EOL 之前删除该空间。
我的代码
$refresheddata = str_replace("\n", '<br>', $data);
样本输入
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>
【问题讨论】:
-
为什么不使用
nl2br()? -
@Quirel 它仍然无法处理空格字符
-
既然你生成 HTML,
<br>之前的空格就无所谓了。
标签: php html str-replace