如何通过文本中所有括号之间的php preg_replace删除空格

问题描述:

I have the The similar text:

"Eat [ 12 ] my [ 15] shorts [ 20 ]"

And I would like to remove whitespace from all brackets in string.

I tried something like:

$str = 'Eat [ 12 ] my [ 15]  shorts [ 20 ]';
$str = preg_replace_callback("~\([^\)]*)\)~", function($s) {
    return str_replace(" ", "", "($s[1])");
}, $str);
echo $str;

But still without succes.

Could somebody tell my, how to do this right way please?

Many thanks for any help.

我有类似的文字: p>

“ 吃[12]我的[15]短裤[20]“ p> blockquote>

我想从字符串中的所有括号中删除空格。 p> \ n

我尝试了类似的东西: p>

  $ str ='Eat [12] my [15] short [20]'; 
 $ str = preg_replace_callback(“〜  \([^ \]] *)\)〜“,函数($ s){
返回str_replace(”“,”“,”($ s [1])“); 
},$ str);  
echo $ str; 
  code>  pre> 
 
 

但仍然没有成功。 p>

有人可以告诉我,如何正确地做到这一点请 ? p>

非常感谢您的帮助。 p> div>

Try this:

$str = 'Eat [ 12 ] my [ 15]  shorts [ 20 ]';
$str = preg_replace('#\[\s+#', '[', $str);
$str = preg_replace('#\s+\]#', ']', $str);

If you know, that there is going to be only one white space, you can use simple str_replace. That will be a lot faster then preg_replace:

$str = str_replace( array( '[ ', ' ]' ), array( '[', ']' ), $str );