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

Categories

0 votes
538 views
in Technique[技术] by (71.8m points)

regex - Replace excess whitespaces and line-breaks with PHP?

$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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...