【问题标题】:How to trim each line in a heredoc (long string) in PHP如何在 PHP 中修剪 heredoc(长字符串)中的每一行
【发布时间】:2009-10-31 18:20:33
【问题描述】:

我正在寻找一个 PHP 函数,它可以修剪长字符串中的每一行。

例如,

<?php
$txt = <<< HD
    This is text.
          This is text.
  This is text.
HD;

echo trimHereDoc($txt);

输出:

This is text.
This is text.
This is text.

是的,我知道 trim() 函数,但我只是不确定如何在诸如 heredoc 之类的长字符串上使用它。

【问题讨论】:

  • 感谢所有解决方案。我需要学习更多的正则表达式。

标签: php string


【解决方案1】:
function trimHereDoc($t)
{
    return implode("\n", array_map('trim', explode("\n", $t)));
}

【讨论】:

  • +1 因为更通用的解决方案。 (但是,我不喜欢这么紧凑的线条)
  • 请注意,这也会去除可能与换行符 (\n) 配对的任何返回字符 (\r)。源文件可以用 DOS 或 Apple 行结尾编写,但修剪后的行都将具有 Unix 行结尾。你可以在explode()语句的第一个参数中设置你最终想要的行尾。
  • 如果你试图从字符串中修剪换行符,只需在 implode 函数中省略 "\n" 参数: return implode(array_map('trim', explode("\n", $ t)));
【解决方案2】:
function trimHereDoc($txt)
{
    return preg_replace('/^\s+|\s+$/m', '', $txt);
}

^\s+ 匹配行首的空格,\s+$ 匹配行尾的空格。 m 标志表示要进行多行替换,因此 ^$ 将匹配多行字符串的任何一行。

【讨论】:

  • 不错的 RE。需要保留这个的sn-ps。
  • 这个函数实际上是不正确的,因为它也会以混乱的方式删除空行。正确的方式是使用“/^[ \t\f]+|[ \t\f]+$/m”作为pattern。
【解决方案3】:

简单的解决方案

<?php
$txtArray = explode("\n", $txt);
$txtArray = array_map('trim', $txtArray);
$txt = implode("\n", $txtArray);

【讨论】:

    【解决方案4】:
    function trimHereDoc($txt)
    {
        return preg_replace('/^\h+|\h+$/m', '', $txt);
    }
    

    \s+ 删除空行,而 \h+ 保留每个空行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      相关资源
      最近更新 更多