问题
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