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

发布于 2024-10-26 22:23:54 字数 212 浏览 4 评论 0原文

我真的完全不懂正则表达式,这让我很头疼。

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

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

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

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

I really don't understand regex at all, and it hurts my head.

I've a bit of text which looks like this

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

...and I don't really understand how to extract this using PHP's preg_split, or equivalent, command.

How do I do this? And where's a good place to understand how preg works?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

对你的占有欲 2024-11-02 22:23:54

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

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

基本上,我使用的模式搜索:

  • 一个开头 ( ;但是 as ( 具有特殊含义,必须转义: \(
  • 一个或多个不是的字符右括号:[^\)]+
    • 这已被捕获,因此我们稍后可以使用它:([^\)]+)
    • 第一个(并且仅在此处)捕获的内容将作为 $matches[1]
  • 结束 ) ;在这里,它也是一个必须转义的特殊字符:\)

Something like this should do the trick, to match what is between ( and ) :

$str = "blah blah blah (here is the bit I'd like to extract)";
if (preg_match('/\(([^\)]+)\)/', $str, $matches)) {
    var_dump($matches[1]);
}

And you'd get :

string 'here is the bit I'd like to extract' (length=35)

Basically, the pattern I used searches for :

  • An opening ( ; but as ( has a special meaning, it has to be escaped : \(
  • One or more characters that are not a closing parenthesis : [^\)]+
    • This being captured, so we can use it later : ([^\)]+)
    • And this first (and only, here) captured thing will be available as $matches[1]
  • A closing ) ; here, too, it's a special character that has to be escaped : \)
没︽人懂的悲伤 2024-11-02 22:23:54
<?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";
}
<?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";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文