5 回答

TA貢獻1811條經驗 獲得超6個贊
我已經嘗試過這種方法,我得到了你想要的輸出
// 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 lines
foreach($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

TA貢獻1789條經驗 獲得超10個贊
我的方法是:
在新行上分解文本
修剪數組中的每個值
清空每個具有值的數組項
用新線內爆
生成以下代碼:
$chunks = explode(PHP_EOL, $text);
$chunks = array_map('trim', $chunks);
foreach (array_keys($chunks, ' ') as $key) {
$chunks[$key] = '';
}
$text = implode(PHP_EOL, $chunks);

TA貢獻1887條經驗 獲得超5個贊
也許是這樣的:
$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);
?>

TA貢獻1793條經驗 獲得超6個贊
如果您知道行尾字符,并且您的行后始終跟著一個新行:
<?php
$text = '
hello world
hello
';
print str_replace(" \n", "\n", $text);
輸出(此處的格式設置中丟失了一些初始空格):
hello world
hello
警告:任何以其他內容結尾的行也會受到影響,因此這可能不能滿足您的需求。

TA貢獻1783條經驗 獲得超4個贊
為此,您可以使用正則表達式,將 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
"""
>>>
- 5 回答
- 0 關注
- 160 瀏覽
添加回答
舉報