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

时间:2016-07-24 19:42:21

标签: php string replace preg-replace

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

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

4 个答案:

答案 0 :(得分:1)

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

结果

header('Location: /signup');

演示Demo link

答案 1 :(得分:1)

最简单的解决方法是在preg_replace()内使用preg_replace_callback()而不进行任何循环或单独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)

答案 2 :(得分:0)

我认为只用一个正则表达式就可以做到这一点。

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

最好的方法是简单的方法 - 只需逐步浏览字符串的字符,当达到a时递增一个值(当你到达a时递减)。如果值为0,则将字符添加到缓冲区;否则,先检查它是否是空格。

答案 3 :(得分:0)

尝试使用以下内容:

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();

    finishView = ((View) getParent()).findViewById(revealViewId);
    ...
}
相关问题