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("\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
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("\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>
` doesn't matter. – axiac Oct 07 '17 at 10:26