从字符串的一部分中删除空格

Remove whitespace from part of a string

在下面的字符串中,如何去掉括号内的空格?

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

根据Poiz的回答,我修改了代码供个人使用:

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

我认为使用单个正则表达式是不可能的。

应该可以抓取任何括号的内容,preg_replace所有space然后重新插入到原始字符串中。如果您必须经常这样做,这可能会很慢。

最好的方法是简单的方法 - 简单地遍历字符串的字符,在到达 a ( 时递增一个值,在到达 a 时递减一个值)。如果该值为 0,则将该字符添加到您的缓冲区;否则,首先检查它是否是 space。

在这种情况下你可以使用 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

尝试使用以下方法:

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

最简单的解决方法是在 preg_replace_callback() 中使用 preg_replace(),无需任何循环或单独的 replace-functions,如下所示。优点是您可以在 (parenthesis) 中包含不止一组字符串,如下例所示。顺便说一下,您可以测试一下 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)