Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

php - Regex for text between double square brackets

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...