akinuri akinuri - 3 months ago 11x
PHP Question

Remove whitespace from part of a string

In the following string, how can I remove the spaces inside the parentheses?

"The quick brown fox (jumps over the lazy dog)"

Desired output:

"The quick brown fox (jumpsoverthelazydog)"

I'm guessing I need to use regex. I need to target the inside of the parentheses. Following would remove everything in the parentheses including the parentheses.

preg_replace("/\(.*?\)/", "", $string)

And this doesn't work:

preg_replace("/\(\s\)/", "", $string)

I admit, regular expression isn't my strong suit. How can I target only the inside of the parentheses?

Note: Above string is only for demonstration. Actual string and the position of the parentheses vary. Following cases are possible:

"The quick brown fox (jumps over the lazy dog)"

"The quick (brown fox jumps) over (the lazy dog)"

"(The quick brown fox) jumps over the lazy dog"

Using Poiz's answer, I've modifed the code for personal use:

function empty_parantheses($string) {
return preg_replace_callback("<\(.*?\)>", function($match) {
return preg_replace("<\s*>", "", $match[0]);
}, $string);


The easiest work-around would be to use preg_replace() within preg_replace_callback() without any looping or separate replace-functions as shown below. The advantage is that you could have even more than one group of strings wrapped inside (parenthesis) as the example below shows.. and, by the way, you may test it out here.


    $str  = "The quick brown fox (jumps over the lazy dog) and (the fiery lion caught it)";

    $str  = preg_replace_callback("#\(.*?\)#", function($match)  {
        $noSpace    = preg_replace("#\s*?#", "", $match[0]);
        return $noSpace;
    }, $str);

    // PRODUCES:: The quick brown fox (jumpsoverthelazydog) and (thefierylioncaughtit)' (length=68)