Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

$string = "My    text       has so    much   whitespace    




Plenty of    spaces  and            tabs";

echo preg_replace("/ss+/", " ", $string);

I read the PHP's documentation and follow the preg_replace's tutorial, however this code produce

My text has so much whitespace Plenty of spaces and tabs

How can I turn it into :

My text has so much whitespace
Plenty of spaces and tabs

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
531 views
Welcome To Ask or Share your Answers For Others

1 Answer

First, I'd like to point out that new lines can be either , , or depending on the operating system.

My solution:

echo preg_replace('/[ ]+/', ' ', preg_replace('/[
]+/', "
", $string));

Which could be separated into 2 lines if necessary:

$string = preg_replace('/[
]+/', "
", $string);
echo preg_replace('/[ ]+/', ' ', $string);

Update:

An even better solutions would be this one:

echo preg_replace('/[ ]+/', ' ', preg_replace('/s*$^s*/m', "
", $string));

Or:

$string = preg_replace('/s*$^s*/m', "
", $string);
echo preg_replace('/[ ]+/', ' ', $string);

I've changed the regular expression that makes multiple lines breaks into a single better. It uses the "m" modifier (which makes ^ and $ match the start and end of new lines) and removes any s (space, tab, new line, line break) characters that are a the end of a string and the beginning of the next. This solve the problem of empty lines that have nothing but spaces. With my previous example, if a line was filled with spaces, it would have skipped an extra line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...