php如何修剪heredoc中的每一行(长字符串)

Yad*_*ada 10 php string

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

例如:

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

echo trimHereDoc($txt);
Run Code Online (Sandbox Code Playgroud)

输出:

This is text.
This is text.
This is text.
Run Code Online (Sandbox Code Playgroud)

是的,我知道trim()函数.只是不确定如何在像heredoc这样的长字符串上使用它.

gpi*_*ino 27

function trimHereDoc($t)
{
    return implode("\n", array_map('trim', explode("\n", $t)));
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ica 10

function trimHereDoc($txt)
{
    return preg_replace('/^\s+|\s+$/m', '', $txt);
}
Run Code Online (Sandbox Code Playgroud)

^\s+匹配行开头的\s+$空格并匹配行尾的空格.该m标志表示,做多线路替代品,因此^,并$会匹配多行字符串的任何行.

  • 这个函数实际上是不正确的,因为它也会以混乱的方式删除空行.正确的方法是使用"/ ^ [\ t\f] + | [\ t\t\f] + $/m"作为模式. (2认同)

ere*_*non 6

简单解决方案

<?php
$txtArray = explode("\n", $txt);
$txtArray = array_map('trim', $txtArray);
$txt = implode("\n", $txtArray);
Run Code Online (Sandbox Code Playgroud)


jok*_*mer 6

function trimHereDoc($txt)
{
    return preg_replace('/^\h+|\h+$/m', '', $txt);
}
Run Code Online (Sandbox Code Playgroud)

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