Regex for text between double square brackets

老子叫甜甜 提交于 2020-02-08 04:53:11

问题


this is my sample text:

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"}}]]

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

This is my approach:

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?


回答1:


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];
}

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.




回答2:


You're trying to process JSON data using a regular expressions. That's fraught with danger.

Use json_decode



来源:https://stackoverflow.com/questions/34981306/regex-for-text-between-double-square-brackets

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