How do you trim white space on beginning and the e

2020-02-11 11:39发布

问题:

How do you trim white space on beginning and the end of each new line with PHP or regex?

For instance,

$text = "similique sunt in culpa qui officia 

     deserunt mollitia animi, id est 

  laborum et dolorum fuga   

";

Should be,

$text = "similique sunt in culpa qui officia

deserunt mollitia animi, id est

laborum et dolorum fuga
";

回答1:

Using a regex is certainly quicker for this task. But if you like nesting functions this would also trim whitespace from all lines:

$text = join("\n", array_map("trim", explode("\n", $text)));


回答2:

<textarea style="width:600px;height:400px;">
<?php

$text = "similique sunt in culpa qui officia 

     deserunt mollitia animi, id est 

  laborum et dolorum fuga   

";

echo preg_replace("/(^\s+|\s+$)/m","\r\n",$text);

?>
</textarea>

I added the testarea so you can see the newlines clearly



回答3:

1st solution :

Split your original string with the newline character with explode, use trim on each token, then rebuild the original string ...

2nd solution :

Do a replace with this regular expression \s*\n\s* by \n with preg_replace.



回答4:

You can use any horizontal whitespace character switch and preg_replace function to replace them with nothing:

$text = trim(preg_replace('/(^\h+|\h+$)/mu', '', $text));

If you need preserve whitespace on file ned remove trim or replace with ltrim function



回答5:

Here another regex that trims whitespace on beginning an end of each line..

$text = preg_replace('/^[\t ]+|[\t ]+$/m', '', $text);

See /m modifier



回答6:

Mario's solution works well (thank you for that mario - saved my day). Maybe somebody can explain though why it turned my later checks for cross-platform compatible line breaks such as

    (strstr($text, PHP_EOL))

to FALSE even when the line breaks existed.

Anyway, changing "\n" to PHP_EOL fixed the issue:

    $text = join(PHP_EOL, array_map("trim", explode(PHP_EOL, $text)));