How to remove brackets from string in php?
Asked Answered
S

6

17

I have the following string and would like to use str_replace or preg_replace to remove the brackets but am unsure how. I have been able to remove the opening brackets using str_replace but can't remove the closing brackets.

This is the sting:

$coords = '(51.50972493425563, -0.1323877295303646)';

I have tried:

<?php echo str_replace('(','',$coords); ?>

which removed the opening brackets but am now under the impression that I need preg_replace to remove both.

How does one go about this?

Help appreciated

Sgraffito answered 23/1, 2012 at 13:3 Comment(0)
P
71

Try with:

str_replace(array( '(', ')' ), '', $coords);
Peugia answered 23/1, 2012 at 13:7 Comment(1)
Just a note that this might have unintended consequences. For example, when $coords = "(testing (it) out)" the result is "testing it out" instead of "testing (it) out"; A safer way would probably be to use trim() as suggested by Sarfraz. The str_replace works for this example only because there are not multiple parentheses.Scoreboard
J
51

If brackets always come on beginging and end, you can use trim easily:

$coords = trim($coords, '()');

Result:

51.50972493425563, -0.1323877295303646
Joktan answered 23/1, 2012 at 13:11 Comment(1)
This is remove only ) brackets.Sloppy
A
2
echo str_replace(
     array('(',')'), array('',''), 
     $coords);

or just do str_replace twice....

echo str_replace(')', '', str_replace('(','',$coords));
Annabelannabela answered 23/1, 2012 at 13:8 Comment(0)
R
1

i think you need to write your coords here as a string else you get syntax error ;). Anyway, this is the solution i think.

$coords = "(51.50972493425563, -0.1323877295303646)";

$aReplace = array('(', ')');
$coordsReplaced = str_replace($aReplace , '', $coords);

Greets, Stefan

Rosas answered 23/1, 2012 at 13:11 Comment(0)
S
0

it is easier than you think, str_replace can have an array as first parameter

 <?php echo str_replace(array('(',')'),'',$coords); ?>
Stillhunt answered 23/1, 2012 at 13:8 Comment(0)
E
-2

Here's the accepted answer in more modern PHP syntax:

$string = str_replace(["(", ")"], "", $string);

Bear in mind that - as noted by Kelt in a comment on the accepted answer - this will strip all brackets from a string, so if you wanted to strip only the outer brackets of a string like the OP did, your best bet is:

$string = trim($string, '()');
Einberger answered 29/7 at 19:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.