我有这个:
$text = '
hello world
hello
';
Run Code Online (Sandbox Code Playgroud)
仅当它在自己的行上时如何删除?所以在上面的例子中,第二个 应该被删除。结果应该是:
$text = '
hello world
hello
';
Run Code Online (Sandbox Code Playgroud)
通过str_replace(),我可以:
$text = str_replace(' ', '', $text);
Run Code Online (Sandbox Code Playgroud)
但这将删除 的所有实例 ,而不仅仅是当它在自己的行上时。
我已经尝试过这种方法,我得到了你想要的输出
// 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);
Run Code Online (Sandbox Code Playgroud)
我在本地的输出是这样的:
hello world
hello
Run Code Online (Sandbox Code Playgroud)