簡體   English   中英

雙方括號之間文本的正則表達式

[英]Regex for text between double square brackets

這是我的示例文本:

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

我想提取雙括號之間的文本: [[]]

這是我的方法:

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

但它僅適用於[]等單括號之間的文本。

我的正則表達式如何才能提取雙括號之間的文本?

試試這個 - 第一場比賽:

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

或者這個 - 迭代所有匹配項:

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 這可能會更好。

您正在嘗試使用正則表達式處理 JSON 數據。 那充滿了危險。

使用json_decode

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM