【问题标题】:Extract whatever is in brackets using regular expressions使用正则表达式提取括号中的内容
【发布时间】:2011-07-23 21:06:30
【问题描述】:
我真的一点都不懂正则表达式,这让我很头疼。
我有一些看起来像这样的文本
blah blah blah (here is the bit I'd like to extract)
...我真的不明白如何使用 PHP 的 preg_split 或等效命令来提取它。
我该怎么做?哪里是了解 preg 工作原理的好地方?
【问题讨论】:
标签:
php
regex
preg-match
preg-split
【解决方案1】:
这样的事情应该可以解决问题,以匹配 ( 和 ) 之间的内容:
$str = "blah blah blah (here is the bit I'd like to extract)";
if (preg_match('/\(([^\)]+)\)/', $str, $matches)) {
var_dump($matches[1]);
}
你会得到:
string 'here is the bit I'd like to extract' (length=35)
基本上,我使用的模式搜索:
- 开口
(;但由于 ( 具有特殊含义,必须对其进行转义:\(
- 一个或多个不是右括号的字符:
[^\)]+
- 这个被捕获了,所以我们以后可以使用它:
([^\)]+)
- 第一个(并且仅在此处)捕获的东西将以
$matches[1] 的形式提供
- 结束
);在这里,它也是一个必须转义的特殊字符:\)
【解决方案2】:
<?php
$text = "blah blah blah (here is the bit I'd like to extract)";
$matches = array();
if(preg_match('!\(([^)]+)!', $text, $matches))
{
echo "Text in brackets is: " . $matches[1] . "\n";
}