删除php中确切位置的空白区域

时间:2012-10-10 08:21:37

标签: php position whitespace

我只是想知道如何通过行内的行和位置完全删除空格或甚至字符。我找不到关于此的信息,但我认为PHP trim()可以提供帮助。我也在考虑动态文本的解决方案。在我想要的地方删除所有空的行。或者只是其中一些。

一个例子:

> here is text blabla
> 
> here is text balabla  balabala
> 
1
2 
3 
> oops too much space
> 
> also here is text

现在我该如何剥离3个白色空间?

它必须成为这样的东西:

> here is text blabla
> 
> here is text balabla  balabala
> 
> oops too much space
> 
> also here is text

3 个答案:

答案 0 :(得分:4)

似乎你想要正则表达式:

preg_replace("#(\r?\n){3,}#", "\n\n", $str);

它用两个换行符(一个空行)替换3个换行符或更多行(即两个连续的空行或更多行)。

为了确保它只使用看似空的行(即只包含空格的行),您需要稍微改变表达式:

preg_replace("#(\r?\n\s*){3,}#", "\\1\\1", $str);

免责声明:\\1\\1想法来自NullPointerException:)

您也可以采取不同的路线并迭代解决:

// $final is the result of the operation
// $n keeps track of how many empty lines were seen
$final = ''; $n = 0;
// $str is the original content, we split it into separate lines
foreach (preg_split("/\r?\n/", $str) as $line) {
        if (strlen(trim($line))) {
                $n = 0;
        } elseif (++$n >= 2) {
                continue;
        }
        // append to the final result
        $final .= "$line\n";
}
// rtrim($final, "\n");

事实证明,在上面的迭代解决方案中使用explode()可以提高性能;由于trim(),它仍适用于仅限空格的行。但是,您需要使用rtrim($final, "\n");修剪右侧的换行符。

答案 1 :(得分:1)

不是正则表达式解决方案:

 function stripEmptyNewlines($string,$limit = 1){
     $array = explode("\n",$string);
     $emptyLine = 0;
     $newString = "";
     foreach($array as $child){
         if(trim($child) == "") {
             $emptyLine++;
         } else {
             $emptyLine = 0;
         }
         if($emptyLine < $limit + 1){
             $newString .= "\n" . $child;
         }
     }
     return $newString;
 }

答案 2 :(得分:-1)

在文字上使用ReadLine()方法。

如果是ReadLine()。Trim()!=“”,则将其添加到输出字符串。 (否则它将是一个空行)

相关问题