douying4909 2017-10-07 09:44
浏览 138
已采纳

如何在条件中使用str_replace

I want to use str_replace with some conditions. I am developing an application which inputs a block of text from a text area and output it as 1 line. Whenever an "end of line" or "space + with end of line" is met, the string is replaced by <br>

I have now came with the solution that whenever and end of line is met, the string is replaced by <br>. But if the user types a space before end of line , i need to get rid of that space too before replacing the EOL with <br>.

MY CODE

$refresheddata = str_replace("
", '<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

Check the space before <br>

FULL CODE

<?php 
$page = $data = $title =  $refresheddata = '';
if($_POST){
    $page = $_POST['page'];
    $data = $_POST['data'];
    $title = $_POST['title'];
    $refresheddata = str_replace("
", '<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>
  • 写回答

2条回答 默认 最新

  • dpsu84620 2017-10-09 16:58
    关注

    Finally I got the answer. Since Im using textarea for the input, all other answers are wrong, I still get the space at the EOL. I tried replacing my str_replace functions parameters and got the desired output.

    SOLUTION

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

    Now the new line is gone with the space before it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路