Page 1 of 1

Best way to find two newlines

Posted: Thu Apr 16, 2009 4:07 pm
by socket1
What's the best way to determine if there are two or more newlines or just one in a string.

Example: I have these strings:

$String = "This is \n a string";
I want to replace the \n in this case with a <br />

$String = "This is \n\n a string";
I want to replace the \n\n in this case with a <hr />
or basically if there are more than one \n I want to replace all of them with <hr /> and if there is just one newline I just want it to be replaced with a <br />

Re: Best way to find two newlines

Posted: Thu Apr 16, 2009 4:19 pm
by Christopher

Code: Select all

$String = str_replace("\n\n", "\n", $String);

Re: Best way to find two newlines

Posted: Thu Apr 16, 2009 4:34 pm
by McInfo
First replace the multiple newlines with <hr>, then replace any remaining newlines with <br>.

test_replace.php

Code: Select all

<?php
header('Content-Type: text/plain');
 
echo "-----Original String-----\n";
$string = "one\ntwo\n\nthree\nfour\n\n\n\nfive";
echo $string;
 
echo "\n\n-----Replace Multiple Newlines-----\n";
$string = preg_replace('/\n\n+/', '<hr>', $string);
echo $string;
 
echo "\n\n-----Replace Single Newlines-----\n";
$string = str_replace("\n", "<br>", $string);
echo $string;
?>
Output of test_replace.php The gray text shows the invisible newlines.
-----Original String-----
one\n
two\n
\n
three\n
four\n
\n
\n
\n
five

-----Replace Multiple Newlines-----
one\n
two<hr>three\n
four<hr>five

-----Replace Single Newlines-----
one<br>two<hr>three<br>four<hr>five
Edit: This post was recovered from search engine cache.

Re: Best way to find two newlines

Posted: Thu Apr 16, 2009 4:39 pm
by socket1
Thank you very much.