This thread is very similar, but I dont want to remove white spaces, but any characters. For example, Im trying to remove new lines (0x10 or 0x13 characters) from a string, but if something is around ' ' or " " then it must be remained untouched. Im using php.
Asked
Active
Viewed 148 times
3
-
1While a regexp to do what you want shouldn't be too hard to come up with, it's worth noting that strings (implied by single or doublequotes) may contain escape characters which may destroy your regex (depending on the escape mechanism). For example: `"he said\"hello\"!"` – Christian Jun 05 '12 at 12:20
-
Could you give an example string? – arothuis Jun 05 '12 at 12:23
-
remove @ from it: $a = 'sdfsdf@dsf@ "sdfdsf@sdhereThe@MustBeUnTouched!!" sdfsf@sdf'; – John Smith Jun 05 '12 at 12:24
1 Answers
3
You could do that by replacing the following expression:
("[^"]*"|'[^']*')|[\r\n]+
With the content of the first capturing group: $1
.
This works by capturing the quote and replacing it with it self, or matching the things you want to remove, and replacing them with the empty string.
If you want to handle backslash escapes too, you could use the following expression instead in the same replacement:
("(?:[^"\\]+|\\.)*"|'(?:[^'\\]+|\\.)*')|[\r\n]+

Qtax
- 33,241
- 9
- 83
- 121
-
1You may want `("(?:[^"\\]+|\\.)*"|'(?:[^'\\]+|\\.)*'|\\.)|[\r\n]+`, to also account for escaped characters out of quotes. – Kobi Jun 05 '12 at 12:56
-
1