php - 如何在条件下使用 str_replace

标签 php html str-replace

我想在某些条件下使用 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>
&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);

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

关于php - 如何在条件下使用 str_replace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46618785/

相关文章:

javascript - 为 php 中的每个元素生成唯一的模态

php - 适用于 PHP 的 Azure : "ServiceDefinition.rd" does not exist in Service directory "ServiceDefinition.csx"

jquery - AJAX 按钮提交的 HTML5 表单验证

javascript - 将 javascript 函数应用于相同的 id

qt - 同时替换一个很长的字符串中的多个单词的最快方法是什么

PHP & MySQL - preg_match 和查询

php - 如何通过索引获取 PHP DOMDocument 的子项

html - Spring MVC 表单复选框和标签不对齐

PHP:优化单个字符串中多个字符串的查找和替换过程

php - 如何替换该字符串中的斜杠?