views:

190

answers:

5

Hi All

I would like to be able to remove content from a string of data.

This is an example string from google maps api.

Distance: 70.5&#160;mi (about 1 hour 12 mins)<br/>Map data &#169;2009 Google

I would like everything in between the brackets (). So can I remove everything from either side with preg_split ?

Hope you can advise.

And thank you in advance.

+2  A: 
if (preg_match('/\(([^)]*)\)/', $text, $regs)) {
    $result = $regs[2];
    // $result now contains everything inside the backets
}
rikh
A: 

That's basic regular expression problem. Use something like this: preg_match('/\(.*?\)/', $s, $m); where $s is your string. The matches are going to be in the $m array.

Marko
A: 

You could use preg_replace:

$timeDistance = preg_replace(array('/(.*)([(])(.*)([)])/'), array('\3',''), $googleString );

That should extract the text between the parens.

Doug Hays
+3  A: 

This is better:

$str = "Distance: 70.5&#160;mi (about 1 hour 12 mins)<br/>Map data &#169;2009 Google";

$start = strpos($str, '(') + 1;
$end = strpos($str, ')');
$content = substr($str, $start, $end - $start);

But if you are dead-set on using a regex:

preg_match($str, '/\((.*?)\)/', $matches);
$content = $matches[1];
Matthew Scharley
Thank you very much
Lee
A: 

explode()

// Step 1
$string  = "Distance: 70.5&#160;mi (about 1 hour 12 mins)<br/>Map data &#169;2009 Google";
$pieces = explode("(", $string);
echo $pieces[0]; // should be: Distance: 70.5&#160;mi 
echo $pieces[1]; // should be: about 1 hour 12 mins)<br/>Map data &#169;2009 Google";

// Step 2
$keeper = explode(")", $pieces[1]);
echo $keeper[0]; // should be: about 1 hour 12 mins 
echo $keeper[1]; // <br/>Map data &#169;2009 Google";
Phill Pafford
This one's a `$keeper`... But do you need those two arrays? Really?
Matthew Scharley