PHP 正则表达式:从开头和结尾删除所有字符

时间:2021-01-06 19:51:30

标签: php regex

目的是从字符串中删除所有开始和结束的 \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

问题:

  1. 我上面的 PHP 代码有什么问题?为什么我不能只用中间部分替换全文?我真的应该删除开始/结束而不是用中间部分替换吗?
  2. 当我使用正则表达式 /^(\\n)*(.*)(\\n)*$/ 而不是上面给出的表达式时,我有什么缺点吗?在上面的正则表达式中,我尝试“以 \n 开头 - 除 \n 之外的任何字符 - 想要的任何字符但不以 \n 结尾 - 以 \n 结尾”。在较短的表达式中,我只在开始和结束时列出一个或多个 \n。但这可能是一个问题,例如只有在开始/结束的许多 \n 中的一个会被替换,而有些不会被替换?是否可以保证 \n 不会成为中间 (.*) 的一部分?

使用解决方案进行编辑

  1. 解决方案:这个基本示例也可以用 PHP trim 函数解决。 (就我而言,preg_replace 有一个特殊的原因,所以对我来说this answer from ryszard-czech worked
  2. 注意:字符串$text必须带双引号",不能带单引号',因为在PHP中存在显着差异!

1 个答案:

答案 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
相关问题