如何使用PHP或regex在每行的开头和结尾处修剪空白 [英] How do you trim white space on beginning and the end of each new line with PHP or regex

查看:75
本文介绍了如何使用PHP或regex在每行的开头和结尾处修剪空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用PHP或regex修剪每行新行的开头和结尾的空格?

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

例如,

$text = "similique sunt in culpa qui officia 

     deserunt mollitia animi, id est 

  laborum et dolorum fuga   

";

应该是

$text = "similique sunt in culpa qui officia

deserunt mollitia animi, id est

laborum et dolorum fuga
";

推荐答案

使用正则表达式无疑可以更快地完成此任务.但是,如果您喜欢嵌套函数,那么这也将在所有行中 trim 空格:

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

这篇关于如何使用PHP或regex在每行的开头和结尾处修剪空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆