redrom
redrom

Reputation: 11642

How to remove whitespace via php preg_replace between all brackets in text

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.

Upvotes: 0

Views: 650

Answers (2)

Peon
Peon

Reputation: 8030

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

Upvotes: 0

Matteo Tassinari
Matteo Tassinari

Reputation: 18584

Try this:

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

Upvotes: 2

Related Questions