Skip to content
PHP Logo

What are some best practices for removing extra blank lines between sentences in PHP?

When working with PHP, you can remove extra blank lines between sentences by using the preg_replace function with a regular expression. The regular expression pattern "/(\s*\R){2,}/" can be used to match two or more consecutive blank lines and replace them with just one. This will help clean up the text and make it more readable.

php
$text = "This is a sentence.\n\n\nThis is another sentence.\n\n\n\n\nThis is a third sentence.";
$cleaned_text = preg_replace("/(\s*\R){2,}/", "\n", $text);

echo $cleaned_text;