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
480 views
in Technique[技术] by (71.8m points)

php - Replace multiple newlines, tabs, and spaces

I want to replace multiple newline characters with one newline character, and multiple spaces with a single space.

I tried preg_replace("/ +/", " ", $text); and failed!

I also do this job on the $text for formatting.

$text = wordwrap($text, 120, '<br/>', true);
$text = nl2br($text);

$text is a large text taken from user for BLOG, and for a better formatting I use wordwrap.

question from:https://stackoverflow.com/questions/6360566/replace-multiple-newlines-tabs-and-spaces

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

1 Answer

0 votes
by (71.8m points)

In theory, you regular expression does work, but the problem is that not all operating system and browsers send only at the end of string. Many will also send a .

Try:

I've simplified this one:

preg_replace("/(
?
){2,}/", "

", $text);

And to address the problem of some sending only:

preg_replace("/[
]{2,}/", "

", $text);

Based on your update:

// Replace multiple (one ore more) line breaks with a single one.
$text = preg_replace("/[
]+/", "
", $text);

$text = wordwrap($text,120, '<br/>', true);
$text = nl2br($text);

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

...