Page 1 of 1

Regular expression x remove \n\r to text

Posted: Sat Feb 17, 2007 11:40 am
by webstyler
Hi, I must transform html template into txt template

but I have any problem to make this regular expression:

remove all \n{2,}

for remove more than 2 occurencies of \n or \n\r

?

tx

Posted: Sat Feb 17, 2007 12:19 pm
by neophyte

Code: Select all

^.*$
I believe this expression would match any character on a line. But not line breaks.

You should download regex coach:

http://weitz.de/regex-coach/#install

That will allow you to test your expressions on your desktop.

This site is a great resource too:

http://regular-expressions.info

Posted: Sat Feb 17, 2007 12:25 pm
by webstyler
neophyte wrote:

Code: Select all

^.*$
I believe this expression would match any character on a line. But not line breaks.

You should download regex coach:

http://weitz.de/regex-coach/#install

That will allow you to test your expressions on your desktop.

This site is a great resource too:

http://regular-expressions.info
Hi, thks for info :)

But, I need to replace more than 2 > \n\r in a single \n

tx

Posted: Sat Feb 17, 2007 12:36 pm
by feyd
Regular expression questions belong in the regex forum. :?

Posted: Sat Feb 17, 2007 4:26 pm
by Chris Corbyn
Would that be, turn all \r\n into just \n? \n\r isn't used anywhere as far as I know.

Code: Select all

preg_replace("~\r(?=\n)~", "\n", $text);
If that's not what you meant, you'll need to give some examples as I don't seem to understand what you meant ;)

Posted: Sun Feb 18, 2007 10:23 am
by GeertDD
d11wtq wrote:Would that be, turn all \r\n into just \n?

Code: Select all

preg_replace("~\r(?=\n)~", "\n", $text);
If I'm not mistaken your regex is turning \r\n into \n\n. Remember that lookarounds don't 'consume' text.

Code: Select all

// Try:
preg_replace('~\r(?=\n)~', '', $text);

Posted: Sun Feb 18, 2007 10:37 am
by webstyler
d11wtq wrote:Would that be, turn all \r\n into just \n? \n\r isn't used anywhere as far as I know.

Code: Select all

preg_replace("~\r(?=\n)~", "\n", $text);
If that's not what you meant, you'll need to give some examples as I don't seem to understand what you meant ;)
tx

we must replace all >2 occurencies of \r OR \n OR \r\n OR \n\r with a single \n

tx

Posted: Sun Feb 18, 2007 11:21 am
by Chris Corbyn

Code: Select all

preg_replace("~[\r\n]{2,}~", "\n", $text);
?

Posted: Sun Feb 18, 2007 11:41 am
by GeertDD
That regex would also turn a single occurrence of \r\n into \n.

Credits for the code below goes to the WordPress coders. These lines can be found in the auto_p() function:

Code: Select all

$pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines 
	$pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates