1

im trying to replace a remove unnessary new lines with preg-replace but my regex is incorrect. Anyone any ideas whats wrong with my regex? (i have Apache/2.0.54 & PHP/5.2.9

NOW HAVE:

{
blaa {
blow;
blue};
bell;}
}ball

WOULD LIKE:

{blaa {blow;blue};bell;}}ball

These regex dont work, they remove too much or toolitle??

$buffer = preg_replace('#/\}\n|\r|\s/#s', '}', $buffer);
$buffer = preg_replace('#/\{\n|\r|\s/#s', '{', $buffer);
$buffer = preg_replace('#/\;\n|\r|\s/#s', ';', $buffer);

/g (global) gives blanc content and without the # it doestnt do anything. strange?! Anybody any clue why these dont work?

1
  • 1
    \s does already contain \r and \n. Commented Dec 13, 2010 at 17:08

3 Answers 3

1

If you want to remove any whitespace after {, }, and ;, do this:

preg_replace('/([{};])\s+/', '$1', $buffer)

Here / are the delimiters; ([{};]) describes one character of {, }, and ; while the match is captured; and \s+ describes any following whitespace characters (already including \r and \n).

1
  • Thanks Gumbo for the explanation as well!! Commented Dec 13, 2010 at 17:45
1

This works for me:

$buffer = preg_replace('/\}\\n|\\r|\\s/', '', $buffer);
1
  • The OP was already using single-quoted strings, so the backslashes were not the problem. (Doubling them actually had no effect; the PHP parser just removes the extras before the regex parser ever sees them.) Commented Dec 13, 2010 at 19:53
1
$buffer = preg_replace('#([{};])(?:\n|\r|\s)#s', '$1', $buffer);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.