PHP Regex removes unnecessary data

I would like to remove content from a data row.

This is an example line 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 that I can remove everything from either side with preg_split

?

0


source to share


5 answers


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 in the mood to use regex:

preg_match($str, '/\((.*?)\)/', $matches);
$content = $matches[1];

      

+4


source


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

      



+2


source


This is the main problem with regex. Use something like this: preg_match('/\(.*?\)/', $s, $m);

where $s

is your string. The matches will be in an array $m

.

0


source


You can use preg_replace

:

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

      

This should extract the text between the parens.

0


source


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

      

0


source







All Articles