Reputation: 11642
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
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
Reputation: 18584
Try this:
$str = 'Eat [ 12 ] my [ 15] shorts [ 20 ]';
$str = preg_replace('#\[\s+#', '[', $str);
$str = preg_replace('#\s+\]#', ']', $str);
Upvotes: 2