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 />
Best way to find two newlines
Moderator: General Moderators
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: Best way to find two newlines
Code: Select all
$String = str_replace("\n\n", "\n", $String);(#10850)
Re: Best way to find two newlines
First replace the multiple newlines with <hr>, then replace any remaining newlines with <br>.
test_replace.php
Output of test_replace.php The gray text shows the invisible newlines.
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;
?>Edit: This post was recovered from search engine cache.-----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
Last edited by McInfo on Mon Jun 14, 2010 3:06 pm, edited 1 time in total.
Re: Best way to find two newlines
Thank you very much.