我有一个字符串来源,通常看起来像这样
word1
phrase with more words than one
a phrase prefaced by whitespace that is not whitespace in code
wordX
Run Code Online (Sandbox Code Playgroud)
注意!单词和短语之前的空格以肉眼的空白形式出现,但未使用"trim()"进行修剪.
有没有办法使用Trim()或preg_replace()来保持短语中的空格,但在外面修剪它(看起来像空格但不是).
编辑:我不知道单词和短语之前和之后的空白空间是什么"char".
这会将所有空格字符(空格,制表符和换行符)替换为单个空格:
$output = preg_replace('!\s+!', ' ', $input);
编辑:
对于第一个空格,您可以使用trim()它,也可以使用它:
$output = preg_replace('!^\s+!', '', preg_replace('!\s+!', ' ', $input));
我认为它可以作为一个RegExp完成,如果一个RegExpu大师设法做到这一点,我希望这个人接受他的答案.