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



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

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

期望输出:

"The quick brown fox (jumpsoverthelazydog)"

我想我需要使用regex。我需要瞄准括号的内侧。下面将删除括号中的所有内容,包括括号。

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_callback()中使用preg_replace(),而不进行任何循环或分离replace-functions,如下所示。其优点是,您甚至可以在(括号)内封装多组字符串,如下例所示。。顺便说一下,你可以在这里测试一下。

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

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

演示演示链接

我认为这不可能用一个正则表达式实现。

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

最好的方法是简单的方法——简单地遍历字符串的字符,当达到a时增加一个值(当达到a则减少)。如果值为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;
}   

最新更新