简体   繁体   中英

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.

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. 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

I believe this is what you are looking for.

  • use preg_quote to avoid forgetting to escape certain characters, like the "." in your expression. I'm sure that mostly broke it.
  • Use the case insensitive 'i' modifier, instead of a-zA-Z
  • as Ross said, add \\r and \\n

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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