4

I have a form with a text area, I need to remove from the string entered here eventuals multiple spaces and multiple new lines.
I have written this function to remove the multiple spaces

function fix_multi_spaces($string)
{
    $reg_exp = '/\s+/';
    return preg_replace($reg_exp," ",$string);
}

This function works good for spaces, but it also replace the new lines changing them into a single space.
I need to change multiple spaces into 1 space and multiple new lines into 1 new line.
How can I do?

0

3 Answers 3

6

Use

preg_replace('/(( )+|(\\n)+)/', '$2$3', $string);

This will work specifically for spaces and newlines; you will have to add other whitespace characters (such as \t for tabs) to the regex if you want to target them as well.

This regex works by matching either one or more spaces or one or more newlines and replacing the match with a space (but only if spaces were matched) and a newline (but only if newlines were matched).

Update: Turns out there's some regex functionality tailored for such cases which I didn't know about (many thanks to craniumonempty for the comment!). You can write the regex perhaps more appropriately as

preg_replace('/(?|( )+|(\\n)+)/', '$1', $string);
Sign up to request clarification or add additional context in comments.

1 Comment

You can also use ?| which allows duplicate numbers or ?: which won't capture such as : preg_replace('/(?|( )+|(\\n)+)/', '$1', $string);. Just an FYI, not a critique. php.net/manual/en/regexp.reference.subpatterns.php
-1

You know that \s in regex is for all whitepsaces, this means spaces, newlines, tab etc.

If You would like to replace multiple spaces by one and multiple newlines by one, You would have to rwrite the function to call preg_replace twice - once replacing spaces and once replacing newlines...

Comments

-1

You can use following function for replace multiple space and lines with single space...

function test($content_area){

//Newline and tab space to single space

$content_area = str_replace(array("\r\n", "\r", "\n", "\t"), ' ', $content_area);

// Multiple spaces to single space ( using regular expression)

$content_area = ereg_replace(" {2,}", ' ',$content_area);

return $content_area;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.