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

感情迁移 提交于 2019-12-29 07:15:20

问题


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)));


来源:https://stackoverflow.com/questions/7335060/how-do-you-trim-white-space-on-beginning-and-the-end-of-each-new-line-with-php-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!