【问题标题】:How to use str_replace with a condition如何使用带条件的 str_replace
【发布时间】: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

检查&lt;br&gt;前面的空格

完整代码

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

【问题讨论】:

  • 为什么不使用nl2br()
  • @Quirel 它仍然无法处理空格字符
  • 既然你生成 HTML,&lt;br&gt; 之前的空格就无所谓了。

标签: php html str-replace


【解决方案1】:

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

解决方案

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

现在新行和之前的空格一起消失了。

【讨论】:

    【解决方案2】:

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

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

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

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

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

    【讨论】:

    • 请注意,如果您使用str_replace,则顺序很重要,否则空格不会消失
    • 问题未解决。我已经用完整的代码更新了这个问题。
    • 查看此演示:3v4l.org/ciXIs 该解决方案确实根据您提供的初始上下文工作。通过表单的数据会在一定程度上改变游戏(换行符可能不仅仅是简单的 \n 字符等)
    • 查看这个问题(和答案)以了解您的新问题:stackoverflow.com/questions/7836632/…
    • @Calimero 感谢您的回答。由于我从文本框中获取输入,因此您的解决方案不起作用。我已经搜索并想出了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-29
    • 1970-01-01
    • 2022-05-28
    • 2012-06-12
    相关资源
    最近更新 更多