user4756836
user4756836

Reputation: 1337

regex to remove new line and spaces

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

Upvotes: 5

Views: 7245

Answers (4)

Nirmal Darji
Nirmal Darji

Reputation: 36

Try following

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

Adding global will replace from everywhere.

Upvotes: 1

Majid Shafaei
Majid Shafaei

Reputation: 59

$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"

Upvotes: -1

This shall get rid of empty spaces:

^(?:\s*)(\w+)$  

with multi-line and global modifiers (gm)

Please, if this solved your question mark the question as solved.

Upvotes: 0

SamWhan
SamWhan

Reputation: 8332

I'm not quite sure what you want to achieve here. But if you, as you state in the question, just ** all you have to do is replace \s with nothing. See regex101. (replacing with * for clarity)

The problem with your regex is (besides from it being overly complex ;) that the ending [\r\n]+ requires a CR/LF and, if the line isn't preceded by an empty line (^[\r\n] matches a line beginning with a linefeed - i.e. an empty line), the [\r\n]+ in the first also requires a CR/LF.

In short - it will never match two consecutive non empty lines.

Regards.

Upvotes: 1

Related Questions