1

我真的一点都不懂正则表达式,这让我很头疼。

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

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

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

我该怎么做呢?哪里是了解 preg 工作原理的好地方?

4

2 回答 2

4

像这样的东西应该可以解决问题,以匹配 and 之间的(内容)

$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]
  • 关闭);在这里,它也是一个必须转义的特殊字符:\)
于 2011-03-27T12:25:10.837 回答
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";
}
于 2011-03-27T12:25:15.047 回答