@garyjohnson
have tried every solution I have come across and am still not getting any results. I have a comment box and I am trying to remove all repetative new lines or /r/n from the input.
You need to add Trim() function to do that.
Try this (I haven't test it yet):
$comment = trim(preg_replace('/[\n\r]/', ' ', $comment));
LastMitch
Industrious Poster
4,118 posts since Mar 2012
Reputation Points: 132
Solved Threads: 334
Skill Endorsements: 45
Try using a regular expression to replace multiple instances of CRLF and newline with a single instance. You probably also want to consider including break tags:
// Squeeze break tags
$comment = preg_replace('/(<br\s*\/>)+/', '<br />', $comment);
// Squeeze CRLF
$comment = preg_replace('/(\r\n)+/', '\r\n', $comment);
// Squeeze NL
$comment = preg_replace('/(\n)+/', '\n', $comment);
deceptikon
Challenge Accepted
3,425 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 56
My bad, I should have used double quoted strings:
$comment = preg_replace("/(\r\n)+/", "\r\n", $comment);
deceptikon
Challenge Accepted
3,425 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 56
Post an example of $comment itself. As an example, this works:
<?php
$comment = "test\r\n\r\n\r\nfoo";
$comment = preg_replace("/(\r\n)+/", "\r\n", $comment);
echo $comment;
?>
deceptikon
Challenge Accepted
3,425 posts since Jan 2012
Reputation Points: 822
Solved Threads: 473
Skill Endorsements: 56
@garyjohnson
Try this:
if (isset($_POST['comment'])) {
$comment = $_POST['comment'];
$comment = mysql_real_escape_string($comment);
$comment = filter_var($comment, FILTER_SANITIZE_STRING);
$comment = nl2br($comment);
//this is where it would remove the new lines
$comment = preg_replace("/[\n\r]/",'',$comment);
if($comment == ""){$error=1;}
}
else{ $error = 1;}
I only make 3 minor changes:
Adding this:
$comment = $_POST['comment'];
$comment = mysql_real_escape_string($comment);
and this:
$comment = preg_replace("/[\n\r]/",'',$comment);
I'll haven't test it yet either.
LastMitch
Industrious Poster
4,118 posts since Mar 2012
Reputation Points: 132
Solved Threads: 334
Skill Endorsements: 45
Question Answered as of 3 Months Ago by
deceptikon
and
LastMitch