简体   繁体   English

保留换行符的正则表达式

[英]Regular expression to preserve line breaks

I have a regular expression which allows only certain characters in the message. 我有一个正则表达式,仅允许消息中的某些字符。 What I'm trying to achieve is to allow line breaks as well which will be preserved using nl2br function. 我正在尝试实现的是允许换行以及使用nl2br函数保留的换行符

That's what I have so far: 到目前为止,这就是我所拥有的:

preg_replace('/[^a-zA-Z0-9ńśćółęążź\ .,-]/','',$message)

As far as I have checked, the following expression should preserve line breaks but I'm having problems adding it to the above expression: 据我检查,以下表达式应保留换行符,但在将其添加到上述表达式时遇到问题:

/(\r|\n|\r\n){2,}/

You would just want to add \\r & \\n to the list of characters to not replace. 您只想将\\r\\n添加到不替换的字符列表中。 So: 所以:

preg_replace("/[^a-zA-Z0-9ńśćółęążź\ \.,\-\r\n]/",'',$message)

In the above expression I've also had to change the ' to " (so that \\r & \\n are recognised) but have also had to escape the . and - characters 在上面的表达式中,我还必须将'更改为' (以便识别\\r\\n ),但还必须转义.-字符。

I believe this is what you are looking for. 我相信这就是您要寻找的。

  • use preg_quote to avoid forgetting to escape certain characters, like the "." 使用preg_quote避免忘记转义某些字符,例如“。”。 in your expression. 在你的表情中。 I'm sure that mostly broke it. 我敢肯定,大部分都打破了它。
  • Use the case insensitive 'i' modifier, instead of a-zA-Z 使用不区分大小写的'i'修饰符,而不是a-zA-Z
  • as Ross said, add \\r and \\n 如罗斯所说,添加\\ r和\\ n

print preg_replace('/' . preg_quote('[^a-z0-9ńśćółęążź\\ .,-\\r\\n])') . 打印preg_replace('/'。preg_quote('[^a-z0-9ńśćółęążź\\。,-\\ r \\ n])')。 '/i','',"test\\r\\ntest\\rtest\\ntest"); '/ i','',“ test \\ r \\ ntest \\ rtest \\ ntest”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM