目的是\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
在开始/结束时仅其中之一将被替换而某些将不被替换吗?是否可以保证a\n
不会成为(.*)
中间的一部分?编辑解决方案
trim
函数解决。(在我的情况下,这preg_replace
是有特殊原因的,因此对我来说,来自ryszard-czech的答案很有效)$text
必须用双引号"
而不是单引号,'
因为PHP有很大的不同!采用
$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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句