-
杨魅力
我已经尝试过这种方法,我得到了你想要的输出// Your initial text$text = ' hello world hello';// Explode the text on each new line and get an array with all lines of the text$lines = explode("\n", $text);// Iterrate over all the available linesforeach($lines as $idx => $line) { // Here you are free to do any if statement you want, that helps to filter // your text. // Make sure that the text doesn't have any spaces before or after and // check if the text in the given line is exactly the same is the if ( ' ' === trim($line) ) { // If the text in the given line is then replace this line // with and emty character $lines[$idx] = str_replace(' ', '', $lines[$idx]); }}// Finally implode all the lines in a new text seperated by new lines.echo implode("\n", $lines);我在本地的输出是这样的:hello world hello
-
至尊宝的传说
我的方法是:在新行上分解文本修剪数组中的每个值清空每个具有值的数组项 用新线内爆生成以下代码:$chunks = explode(PHP_EOL, $text);$chunks = array_map('trim', $chunks);foreach (array_keys($chunks, ' ') as $key) { $chunks[$key] = '';}$text = implode(PHP_EOL, $chunks);
-
慕工程0101907
也许是这样的:$text = preg_replace("~(^[\s]?|[\n\r][\s]?)( )([\s]?[\n\r|$])~s","$1$3",$text);http://sandbox.onlinephpfunctions.com/code/f4192b95e0e41833b09598b6ec1258dca93c7f06(这适用于 PHP5,但在某些版本的 PHP7 上却不起作用)替代方案是:<?php $lines = explode("\n",$text); foreach($lines as $n => $l) if(trim($l) == ' ') $lines[$n] = str_replace(' ','',$l); $text = implode("\n",$lines);?>
-
摇曳的蔷薇
如果您知道行尾字符,并且您的行后始终跟着一个新行: <?php$text = ' hello world hello';print str_replace(" \n", "\n", $text);输出(此处的格式设置中丢失了一些初始空格): hello world hello警告:任何以其他内容结尾的行也会受到影响,因此这可能不能满足您的需求。
-
慕娘9325324
为此,您可以使用正则表达式,将 DOTALL 和多行修饰符与环视断言结合使用:preg_replace("~(?sm)(?<=\n)\s* (?=\n)~", '',$text);(?sm): 多点 (s) 多线 (m)(?<=\n):换行符之前(不是匹配项的一部分)\s* \s*: 单次具有可选的周围空格(?=\n):尾随换行符(不是匹配项的一部分)>>> $text = ' hello world hello ';=> """ \n hello world\n \n hello\n """>>> preg_replace("~(?sm)(?<=\n)\s* \s*(?=\n)~", '',$text);=> """ \n hello world\n \n hello\n """>>>