Best way to find two newlines

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
socket1
Forum Commoner
Posts: 82
Joined: Mon Dec 08, 2008 7:40 pm
Location: Shokan, New York

Best way to find two newlines

Post 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 />
User avatar
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

Post by Christopher »

Code: Select all

$String = str_replace("\n\n", "\n", $String);
(#10850)
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: Best way to find two newlines

Post 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.
Last edited by McInfo on Mon Jun 14, 2010 3:06 pm, edited 1 time in total.
socket1
Forum Commoner
Posts: 82
Joined: Mon Dec 08, 2008 7:40 pm
Location: Shokan, New York

Re: Best way to find two newlines

Post by socket1 »

Thank you very much.
Post Reply