Extract whatever is in brackets using regular expressions

不问归期 提交于 2019-12-08 05:40:25

问题


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?


回答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 : \)



回答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";
}


来源:https://stackoverflow.com/questions/5449173/extract-whatever-is-in-brackets-using-regular-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!