从括号内获取文本

问题描述 投票:0回答:5

我希望能够从一串数据中删除内容。

这是来自 google 地图 api 的示例字符串。

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

我想要括号中的所有内容

()
。那么我可以用
preg_split
删除两边的所有内容吗?

php regex string
5个回答
4
投票

这样更好:

$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);

但是如果您执意要使用正则表达式:

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

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

0
投票

这是基本的正则表达式问题。使用类似这样的内容:

preg_match('/\(.*?\)/', $s, $m);
,其中
$s
是你的字符串。匹配项将位于
$m
数组中。


0
投票

你可以使用

preg_replace
:

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

这应该提取括号之间的文本。


0
投票

爆炸()

// 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";
© www.soinside.com 2019 - 2024. All rights reserved.