2016-07-24 19 views
1

在以下字符串中,如何刪除括號內的空格?刪除部分字符串中的空格

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

所需的輸出:

"The quick brown fox (jumpsoverthelazydog)" 

我猜我需要使用正則表達式。我需要將目標放在括號內。以下將刪除括號中括號內的所有內容。

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

而且這不起作用:

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

我承認,正則表達式是不是我的強項。我怎樣才能只針對括號內的內容?


注意:上面的字符串只是爲了演示。實際的字符串和圓括號的位置有所不同。可能出現以下情況:

"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" 

使用ポイズ的回答,我體改供個人使用的代碼:

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

圓括號可以嵌套嗎?如果是這樣,那應該如何處理? – Chris

+0

@Chris不,他們不能。只有內容(字符串)在括號內。 – akinuri

+1

@akinuri試試我的來源。爲我工作得很好! https://開頭3v4l。org/Wija8 –

回答

1

最簡單的解決方法是在preg_replace_callback()之內使用preg_replace(),沒有任何循環或單獨replace-functions,如下所示。優點是你可以在(圓括號)中包含多組字符串,如下面的例子所示..順便說一下,你可以測試它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) 
+0

真的很好,值得借鑑。 –

+0

@QuỳnhNguyễn;-) – Poiz

+0

這似乎是一個更好的方法。我將把它包裝在一個函數中並修改一下。 – akinuri

0

我不認爲這是可能的一個正則表達式。

應該可以抓住任何括號的內容,preg_replace所有空格,然後重新插入到原始字符串中。如果你必須做很多事情,這可能會很慢。

最好的方法是簡單的方法 - 簡單地通過字符串的字符,當你到達一個值時遞增一個值(並且當你到達一個時遞減)。如果該值爲0,則將該字符添加到緩衝區;否則,請先檢查它是否爲空格。

1

您可以在此情況下,使用2 preg_

<?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; 
?> 

結果

The quick (brownfoxjumps) over (thelazydog) 

演示Demo link

+0

''/\(.*?\)/''和''/\(.(.*?).\)/''之間有區別嗎?前者也有效。 – akinuri

+0

@akinuri我認爲它是一樣的。我的參數(。*?)= [棕色狐狸跳躍]。你呢 。*? = [棕色狐狸跳] –

0

嘗試使用以下:

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