Is there a way to remove all white space from document?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
lovelf
Forum Contributor
Posts: 153
Joined: Wed Nov 05, 2008 12:06 am

Is there a way to remove all white space from document?

Post by lovelf »

how could I remove space in blank after ">" character?

sounds simple, I have tried:

Code: Select all

<?php function callback($buffer) {$buffer = str_replace('> ', '>', $buffer); return $buffer;} ob_start("callback"); ?>
But of course it just does not make it, since if there is more than one space after ">" it does not get replaced.

Same for:

Code: Select all

<?php function callback($buffer) {$buffer = str_replace('>
', '>', $buffer); return $buffer;} ob_start("callback"); ?>
In this other one if you have more than one line break inside the document those do not get replaced.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Is there a way to remove all white space from document?

Post by Eran »

Probably inefficient, but will do what you ask:

Code: Select all

<?php
function callback($buffer) {
    while(strpos($buffer,'> ') !== false) {
        $buffer = str_replace('> ', '>', $buffer);
    }
     return $buffer;
} 
ob_start("callback");
lovelf
Forum Contributor
Posts: 153
Joined: Wed Nov 05, 2008 12:06 am

Re: Is there a way to remove all white space from document?

Post by lovelf »

Thanks, that did it :wink:
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Is there a way to remove all white space from document?

Post by requinix »

But if the "> " is positioned one character before the end of the current buffer, the callback will only see a > at the end and the next call will have a space at the beginning.

Code: Select all

$buffer = preg_replace('/>\s+/s', '>', $buffer);
I'd use that on the entire text, not just a part of it.
Post Reply