【发布时间】:2017-06-22 02:00:20
【问题描述】:
我正在使用php function想要创建一个函数来修剪多行字符串中所有不必要的空格。
它不起作用的正则表达式是在末尾删除空格的正则表达式:
// Always trim at the end. Warning: this seems to be the costlier
// operation, perhaps because looking ahead is harder?
$patterns[] = ['/ +$/m', ''];
给定来自文本区域的以下字符串:
first line... abc //<-- blank space here
second is here... def //<-- blank space here
//<-- blank space here
fourth line... hi there //<-- blank space here
sith is here.... //<-- blank space here
每行的开头和结尾有空格,单词之间有多个空格。
运行函数后:
$functions->trimWhitespace($description, ['blankLines' => false]);
这是我得到的:
first line... abc //<-- blank space here
second is here... def //<-- blank space here
//<-- no bank space here
fourth line... hi there //<-- blank space here
sith is here....//<-- no blank space here
为什么只删除最后一行的尾随空格?
【问题讨论】:
-
如果不确定使用的换行符类型,请尝试
'/ +\r?$/m'。 -
既然是PHP,为什么不用
'/\h+$/um' -
@bobblebubble 耶!这就是它所缺少的。我目前在 Linux 中,不确定它是否适用于 Windows 和 Mac。请把解决方案放在答案中。谢谢。
-
@WiktorStribiżew 我已经尝试过那个,但它没有用。我花了几个小时试图找到解决方案。
-
这是否意味着如果 CR 符号存在,您也想删除它?我建议
'/\h+(?=\r?$)/um'