akinuri
akinuri

Reputation: 12027

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);
}

Upvotes: 1

Views: 78

Answers (4)

Poiz
Poiz

Reputation: 7617

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.

<?php

    $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);

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

Upvotes: 1

Quynh Nguyen
Quynh Nguyen

Reputation: 3009

You can use 2 preg_ in this case

<?php
    $string = "The quick (brown fox jumps) over (the lazy dog)";
    //First preg search all string in ()
    preg_match_all('/\(.(.*?).\)/', $string, $match);
    foreach ($match[0] as $key => $value) {
        $result = preg_replace('/\s+/', '', $value);
        if(isset($new_string)){
            $new_string = str_replace($value, $result, $new_string);
        }else{
            $new_string = str_replace($value, $result, $string);
        }

    }
    echo $new_string;
?>

Result

The quick (brownfoxjumps) over (thelazydog)

Demo Demo link

Upvotes: 1

Martijn
Martijn

Reputation: 514

Try using the following:

$str = "The quick (brown fox jumps) over (the lazy dog) asfd (asdf)";
$str = explode('(',$str);
$new_string = '';


foreach($str as $key => $part)
{
       //if $part contains '()'
       if(strpos($part,')') !== false) {
             $part = explode(')',$part);
             //add ( and ) to $part, and add the left-over
             $temp_str = '('.str_replace(' ','',$part[0]).')';
             $temp_str .= $part[1];
             $part = $temp_str;  
       }
       //put everything back together:
       $new_string .= $part;
}   

Upvotes: 0

toneo
toneo

Reputation: 129

I don't think this is possible with a single regular expression.

It should be possible to grab the contents of any brackets, preg_replace all spaces and then re-insert into the original string. This is likely to be quite slow if you have to do it a lot.

The best way is the simple way - simply step through the characters of the string, increment a value when you reach a ( and decrement when you reach a ). If the value is 0, add the character to your buffer; otherwise, check if it's a space first.

Upvotes: 0

Related Questions