如何通过文本中所有括号之间的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.

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