2016-07-24 22 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; 
}