开发者

regex to find text inside first occurrence of tokens "[]"

I'm grabbing a file via file_get_contents($text_file) that has a token in the beginning of the contents in the form...

[widget_my_widget]

The 开发者_开发知识库full contents of the file might be...

[widget_my_widget]
Here is the start of the text file. It may have [] brackets inside it,
but only the first occurrence denotes the token.

I'm looking for the regex to grab the text string inside the first occurrence of the brackets []. In this case, I'd want to return widget_my_widget and load it into my variable.

Thanks in advance for your help.


The first captured group in \[(.+?)\] will match the string inside the square brackets.

In PHP you can use it like this:

if (preg_match('/\[(.+?)\]/', file_get_contents($text_file), $group)) {
    print $group[1];
}

At first occurance in this string (the file content), ignore the left square bracket, then match as little as possible, but up to (not including) the right square bracket.


I think Staffan's answer is mostly correct, but I have a minor correction and I think you may want to avoid the ^, or the string will have to start with a bracket and you said you just want the first instance. On to the code...

$str = ...

$pattern = '/\[([^\]+])\]/';
$n = preg_match($pattern, $str, $matches);
if ($n > 0) {
    $first_match = $matches[1];
    /// do stuff
}

My pattern looks a little confusing because brackets have special meaning, so I'll try to explain it... we're looking for a open bracket, then one or more characters that is not a closing bracket (in this context, the caret means "not"), then a closing bracket. The parenthesis are around the content we want to capture and the inner brackets are a character class. If that makes no sense, just ignore everything I just said.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜