开发者

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

开发者 https://www.devze.com 2023-04-03 11:32 出处:网络
How do you trim white space on beginning and the end of each new line with PHP or regex? For instance,

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 = "s开发者_JAVA技巧imilique sunt in culpa qui officia

deserunt mollitia animi, id est

laborum et dolorum fuga
";


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


<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


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.


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


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

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

See /m modifier


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

精彩评论

暂无评论...
验证码 换一张
取 消