简体   繁体   中英

Regular expression replace characters with the correct number of spaces

I wanna replace with spaces all characters except number, lecters, space and other characters #=<>();*,.+\\/-

eg preg_replace("/[^ #=<>();*,.+\\/-\\w]+/", " ", $string);

My problem is that when in the $string there are two or more consecutive characters to be replaced, the function replace this characters with just one space, while I need that the functions replace the two or more characters with two or more spaces.

Is there a way?

You should match only one character at a time. You must also escape some of the characters.

Change

 preg_replace("/[^ #=<>();*,.+/-\w]+/", " ", $string);

to

 preg_replace("/[^ #=<>();*,\\.+\\/\\-\\w]/", " ", $string);
  • If your character class contains both forward and backward slash, you need to escape both forward and backward slashes which are present inside the character class.

I wanna replace with spaces all characters except number, lecters, space and other characters #=<>();*,.+\\/-

  • \\w represent letters,numbers and also _ symbol. So avoid using \\w inside the character class.

  • As another answer said, you need to remove the + after character class, which replaces one or more characters with a single space.

  • And your regex should be,

     [^- #=<>();*,.+\\\\\\/0-9A-Za-z] 

DEMO

  • In the demo it matches _ symbol because it isn't included in the NOT character class. In the replacement part i gave only a single space. It replaces three _ symbols with three spaces.

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