我希望您能创建一个可以剪切长字符串中每行的 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等长字符串上使用它。
function trimHereDoc($t)
{
return implode("\n", array_map('trim', explode("\n", $t)));
}
function trimHereDoc($txt)
{
return preg_replace('/^\s+|\s+$/m', '', $txt);
}
^\s+
匹配行首的空格,而\s+$
匹配行尾的空格。标志m
表示进行多行替换,因此^
和$
将匹配多行字符串中的任何行。
简单的解决方案
<?php
$txtArray = explode("\n", $txt);
$txtArray = array_map('trim', $txtArray);
$txt = implode("\n", $txtArray);
function trimHereDoc($txt)
{
return preg_replace('/^\h+|\h+$/m', '', $txt);
}
\s+
用于去除空行,而\h+
则保留每个空行。