使用正则表达式提取括号中的任何内容

时间:2011-03-27 12:21:37

标签: php regex preg-match preg-split

我真的根本不理解正则表达式,这让我很痛苦。

我有一些看起来像这样的文字

blah blah blah (here is the bit I'd like to extract)

...我真的不明白如何使用PHP的preg_split或等效的命令来提取它。

我该怎么做?什么是理解preg如何工作的好地方?

2 个答案:

答案 0 :(得分:4)

这样的事情可以解决问题,以匹配()之间的内容:

$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]
    • 的形式提供
  • 结束);在这里,它是一个必须被转义的特殊角色:\)

答案 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";
}
相关问题