我正在寻找一个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
标志表示,做多线路替代品,因此^
,并$
会匹配多行字符串的任何行.
简单解决方案
<?php
$txtArray = explode("\n", $txt);
$txtArray = array_map('trim', $txtArray);
$txt = implode("\n", $txtArray);
Run Code Online (Sandbox Code Playgroud)
function trimHereDoc($txt)
{
return preg_replace('/^\h+|\h+$/m', '', $txt);
}
Run Code Online (Sandbox Code Playgroud)
\s+
删除空行时,保留每个\h+
空行