我希望能够从一串数据中删除内容。
这是来自 google 地图 api 的示例字符串。
Distance: 70.5 mi (about 1 hour 12 mins)<br/>Map data ©2009 Google
我想要括号中的所有内容
()
。那么我可以用 preg_split
删除两边的所有内容吗?
这样更好:
$str = "Distance: 70.5 mi (about 1 hour 12 mins)<br/>Map data ©2009 Google";
$start = strpos($str, '(') + 1;
$end = strpos($str, ')');
$content = substr($str, $start, $end - $start);
但是如果您执意要使用正则表达式:
preg_match($str, '/\((.*?)\)/', $matches);
$content = $matches[1];
if (preg_match('/\(([^)]*)\)/', $text, $regs)) {
$result = $regs[2];
// $result now contains everything inside the backets
}
这是基本的正则表达式问题。使用类似这样的内容:
preg_match('/\(.*?\)/', $s, $m);
,其中$s
是你的字符串。匹配项将位于 $m
数组中。
你可以使用
preg_replace
:
$timeDistance = preg_replace(array('/(.*)([(])(.*)([)])/'), array('\3',''), $googleString );
这应该提取括号之间的文本。
// Step 1
$string = "Distance: 70.5 mi (about 1 hour 12 mins)<br/>Map data ©2009 Google";
$pieces = explode("(", $string);
echo $pieces[0]; // should be: Distance: 70.5 mi
echo $pieces[1]; // should be: about 1 hour 12 mins)<br/>Map data ©2009 Google";
// Step 2
$keeper = explode(")", $pieces[1]);
echo $keeper[0]; // should be: about 1 hour 12 mins
echo $keeper[1]; // <br/>Map data ©2009 Google";