Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove white spaces from everywhere except quotation marks

I'm using '/\s+/' switch in preg_replace to remove all the white spaces from Javascript code, that I pass in PHP array:

preg_replace('/\s+/', '',
("
    function(uploader)
    {
        if(uploader.files.length > 1)
        {
            uploader.files.splice(1, uploader.files.length);

            apprise('You can not update more than one file at once!', {});
        }
    }
"))

This is for an very basic Javascript minification. In PHP file (source) I can have fully readable function code, while in browser, it page body it ends up like single-line string:

function(uploader,files){console.log('[PluploadUploadComplete]');console.log(files);},'QueueChanged':function(uploader){if(uploader.files.length>1){uploader.files.splice(1,uploader.files.length);apprise('Youcannotupdatemorethanonefileatonce!',{});}}

As you can see (or expect) this does affects strings in quotation marks and produce message without spaces (like: Youcannotupdatemorethanonefileatonce!).

Is there a workaround for this problem? Can I remove all whitespaces from everywhere in my string, except for part embedded in single quotation marks?

like image 452
trejder Avatar asked Nov 26 '25 20:11

trejder


2 Answers

To match space characters except within single quotes, use this:

$regex = "~'[^']*'(*SKIP)(*F)|\s+~";

You can pop that straight into your preg_replace().

For instance: $replaced = preg_replace($regex,"",$input);

Option 2: Multiple Kinds of Quotes

If you may have single or double quotes, use this:

$regex = "~(['"]).*?\1(*SKIP)(*F)|\s+~";

How Does this Work?

On the left side of the | alternation, we match full "quoted strings", then deliberately fail, and skip to the next position in the string. On the right side, we match any whitespace, and we know it is the right whitespace because it was not matched by the expression on the left.

Reference

How to match (or replace) a pattern except in situations s1, s2, s3...

like image 86
zx81 Avatar answered Nov 28 '25 09:11

zx81


You could simply capture the single quoted strings and reference it in your replacement. Be aware this will only work for a simple case of single quoted strings, not nested...

$code = preg_replace("/('[^']*')|\s+/", '$1', $code);
like image 20
hwnd Avatar answered Nov 28 '25 10:11

hwnd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!