16

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

Tadeck
  • 132,510
  • 28
  • 152
  • 198
hairynuggets
  • 3,191
  • 22
  • 55
  • 90

5 Answers5

69

Try with:

str_replace(array( '(', ')' ), '', $coords);
hsz
  • 148,279
  • 62
  • 259
  • 315
  • 5
    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. – Kelt Oct 08 '15 at 22:15
50

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

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

Result:

51.50972493425563, -0.1323877295303646
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
2
echo str_replace(
     array('(',')'), array('',''), 
     $coords);

or just do str_replace twice....

echo str_replace(')', '', str_replace('(','',$coords));
symcbean
  • 47,736
  • 6
  • 59
  • 94
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

Stefan Koenen
  • 2,289
  • 2
  • 20
  • 32
0

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

 <?php echo str_replace(array('(',')'),'',$coords); ?>
rauschen
  • 3,956
  • 2
  • 13
  • 13