目的是从字符串中删除所有开始和结束的 \n
。开头和结尾可以没有、一个和多个 \n
,数量独立。
我想过在正则表达式中使用 preg_replace
。但以下测试不起作用:
$text = "asd\nasd\nasd\nasd\n";
//$text = "\n\nasd\nasd\nasd\nasd\n";
$text = preg_replace('/^(\\n)*(?!\\n)(.*)(?<!\\n)(\\n)*$/', '$2', $text);
var_dump($text);
对于 regex101.com,第 2 组(参见上面的 $2
)正好位于字符串的中间,没有开始和结束 \n
。
问题:
/^(\\n)*(.*)(\\n)*$/
而不是上面给出的表达式时,我有什么缺点吗?在上面的正则表达式中,我尝试“以 \n 开头 - 除 \n 之外的任何字符 - 想要的任何字符但不以 \n 结尾 - 以 \n 结尾”。在较短的表达式中,我只在开始和结束时列出一个或多个 \n。但这可能是一个问题,例如只有在开始/结束的许多 \n
中的一个会被替换,而有些不会被替换?是否可以保证 \n
不会成为中间 (.*)
的一部分?使用解决方案进行编辑
trim
函数解决。 (就我而言,preg_replace
有一个特殊的原因,所以对我来说this answer from ryszard-czech worked)$text
必须带双引号"
,不能带单引号'
,因为在PHP中存在显着差异!答案 0 :(得分:1)
使用
$text = preg_replace('/^\n+|\n+\z/', '', $text);
说明
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
\n+ '\n' (newline) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
\n+ '\n' (newline) (1 or more times (matching
the most amount possible))
--------------------------------------------------------------------------------
\z the end of the string