regex to remove new line and spaces

Viewed 5555

I created a regex to get rid of spaces, tabs, new lines, etc.

(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+

My issue is that it matches some spaces and some new lines, not all of them. Why is that?

I have tried:

(^[\r\n]*|[\r\n]+)[\s\t+]*[\r\n]+

but still doesn't seem to match multiple spaces

Regex tester demo

4 Answers

Try following

.replace(/\s+/g, "") .replace(/\n+/g, "")

Adding global will replace from everywhere.

$input_lines = <<<EOD


test

aeee
eeeee
EOD;


$output = preg_replace('/(\s)*/', '$1', $input_lines);
var_dump($output);

Result:

string(16) "
test
aeee
eeeee"

If i want to remove all newline

$output = preg_replace('/(\s)*/', '', $input_lines);
var_dump($output);

Result:

string(13) "testaeeeeeeee"
Related