仅在单独一行时删除术语

15

我有这个:

$text = '
   hello world
    
    hello
';

如果仅当 单独占据一行时,我该如何删除它?因此,对于上面的示例,第二个 应该被删除。结果应为:

$text = '
   hello world

    hello
';

我所尝试的

通过str_replace()函数,我可以:

$text = str_replace(' ', '', $text);

但这样会删除所有 实例,而不仅仅是它自己在一行上时。


6
非常感谢您的留言。您所提到的“Beautiful addition of What I've tried so far - should be standard on this site. +1”可以翻译为“‘我尝试过什么’这个很好的补充应该成为这个网站的标准功能。+1”。 - Gary Woods
2
@misorude 请随意发表您的方法答案。 - Henrik Petterson
3
@FlashThunder,为什么不使用str_replace()来发布答案,而是要评判我的经验呢。=) - Henrik Petterson
1
@FlashThunder 如果使用 str_replace() 不可行,请随意建议其他方法。我的初始路线是使用 str_replace() - Henrik Petterson
2
@misorude 但如果你认为这是一个整个网站的问题,那么你需要在meta社区与其他人讨论。为什么要在这里提出呢? - Henrik Petterson
显示剩余10条评论
6个回答

9

我已经尝试过这种方法,而且得到了您想要的输出结果。

// 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

我认为作者甚至没有意识到其中有一个制表符/几个空格,因为他在另一条评论中询问它后面是否有空格(但实际上并没有)。 - Flash Thunder
@FlashThunder 我知道。我只是在问一个案例示例。 - Henrik Petterson
@HenrikPetterson 但是您想要将它们删除还是不删除?因为您要求删除  ,所以我的解决方案保留了空格。 - Flash Thunder
@FlashThunder现在也维护标签页。 - KodeFor.Me
1
抱歉,这是误操作。 - Flash Thunder
显示剩余5条评论

2

我的方法是:

  1. 将文本按照换行符分割成数组
  2. 去除数组中每个值的空格
  3. 将数组中值为   的项清空
  4. 使用换行符重新组合数组

最终代码如下:

$chunks = explode(PHP_EOL, $text);
$chunks = array_map('trim', $chunks);
foreach (array_keys($chunks, ' ') as $key) {
    $chunks[$key] = '';
}
$text = implode(PHP_EOL, $chunks);

2
你的代码输出与要求不完全相同 :/hello world  hello最初的要求只是将   替换为空文本,而不是删除整行 :/。另外,请记住不是我给你的回答投了反对票 :) 我的评论只是友好的留言 :) - KodeFor.Me
1
现在好多了 :) - KodeFor.Me

2
也许是这样的:

可能是这样的:

$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) == '&nbsp;')
            $lines[$n] = str_replace('&nbsp;','',$l);
    $text = implode("\n",$lines);
?>

1
我测试了一下,不起作用 :)。同时请记住,我没有给你任何负面评价,这只是一个友好的评论 :) 在测试你的解决方案后,输出结果仍然没有改变。 - KodeFor.Me
1
这是我在本地运行你的代码时得到的结果:https://pasteboard.co/IUkf2MK.png :) - KodeFor.Me
2
@MerianosNikos 哦,有趣,可以在PHP5上运行但无法在PHP7上运行。 - Flash Thunder
@MerianosNikos 我刚刚发现一个PHP7的bug?嗯...真奇怪,应该能够工作。 - Flash Thunder
无论如何,当你意识到问题时,我已经为你点赞了 :) xaxaxaxa - KodeFor.Me
显示剩余2条评论

1
如果您知道您的行尾字符,并且您的&nbsp;总是跟随着一个新行:
<?php
$text = '
   hello&nbsp;world
   &nbsp;
   &nbsp;hello
';


print str_replace("&nbsp;\n", "\n", $text);

输出(这里格式化时丢失了一些初始空格):

   hello&nbsp;world

   &nbsp;hello

注意:任何以&nbsp;结尾并且前面有其他内容的行也会受到影响,因此这可能不符合您的需求。

1
如果我们坚持使用str_replace(),这实际上是一个非常稳健的解决方案! - Henrik Petterson
@Progrock 有没有可能调整一下,在计算 &nbsp; 后面的空格时也要将其考虑在内?比如:"&nbsp; \n" - Henrik Petterson
@HenrikPetterson 不。 - Flash Thunder

1
你可以使用正则表达式来实现,同时使用DOTALL和MULTILINE修饰符以及环视断言:
preg_replace("~(?sm)(?<=\n)\s*&nbsp;(?=\n)~", '',$text);
  • (?sm): DOTALL(s)MULTILINE(m)
  • (?<=\n): 前导换行符(不包括在匹配中)
  • \s*&nbsp;\s*: 单个&nbsp;,可选周围空格
  • (?=\n): 尾随换行符(不包括在匹配中)
>>> $text = '                                                                                               
 hello&nbsp;world                                                                                         
 &nbsp;                                                                                                   
 &nbsp;hello                                                                                           
 ';
=> """
   \n
      hello&nbsp;world\n
      &nbsp;\n
      &nbsp;hello\n
   """
>>> preg_replace("~(?sm)(?<=\n)\s*&nbsp;\s*(?=\n)~", '',$text);
=> """
   \n
      hello&nbsp;world\n
   \n
      &nbsp;hello\n
   """
>>>

0

你可以将文本分成多行,然后在只包含&nbsp;和空格的行上用空字符串替换&nbsp;

我们会保留原始的行结束符,通过捕获它们。

<?php

$text = '
   hello&nbsp;world
   &nbsp;
   &nbsp;hello
';
$lines = preg_split('@(\R)@', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach($lines as &$v)
    if (trim($v) === '&nbsp;')
        $v = str_replace('&nbsp;', '', $v);

$result = implode($lines);
var_dump($result);

输出:

string(40) "
   hello&nbsp;world

   &nbsp;hello
"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接