jacek_podwysocki
jacek_podwysocki

Reputation: 807

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,}/

Upvotes: 2

Views: 2165

Answers (2)

Wouter
Wouter

Reputation: 1987

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");

Upvotes: 1

Ross McLellan
Ross McLellan

Reputation: 1881

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

Upvotes: 3

Related Questions