双方括号之间文本的正则表达式 [英] Regex for text between double square brackets

查看:104
本文介绍了双方括号之间文本的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的示例文本:

text text text
[[{"fid":"3228","view_mode":"full","fields":{"format":"full","field_file_image_alt_text[und][0][value]":"text text text","field_file_image_title_text[und][0][value]":"","field_file_image_gallery_content[und][0][value]":"","field_file_image_gallery_content[und][0][format]":"full_html"},"type":"media","link_text":null,"attributes":{"alt":"text text","height":"647","width":"421","class":"media-element file-full"}}]]

我想提取双括号之间的文本:[[ and ]].

I want to extract the text between the double brackets: [[ and ]].

这是我的方法:

preg_match_all("/\[[^\]]*\]/", $txt, $matches);

但它仅适用于[] 等单括号之间的文本.

But it works only for text between singles brackets like [ and ].

我的正则表达式要如何提取双括号之间的文本?

How does my regex to have to look like, to extract the text between double brackets?

推荐答案

试试这个 - 第一个匹配:

Try this - first match:

if (preg_match('/\[\[(.*?)\]\]/i', $buffer, $regs)) {
    $result = $regs[1];  // Matched text
} else {
    $result = "";
}

或者这个 - 迭代所有匹配:

Or this - iteration over all matches:

preg_match_all('/\[\[(.*?)\]\]/i', $buffer, $regs, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($regs[1]); $i++) {
    // Matched text = $regs[1][$i];
}

如果您没有真正的论据来处理这样的数据,请按照 Borodin 的回答并使用 json_decode.这可能会更好.

If you have no real argument to process the data like this, follow Borodin's answer and use json_decode. This probably would be better.

这篇关于双方括号之间文本的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆