簡體   English   中英

使用php preg_match從論壇報價中獲取ID

[英]Using php preg_match to get an id from forum quotes

我一直在使用preg_match嘗試從我撰寫的論壇中的報價中獲取ID。 到目前為止,這就是我所擁有的。

$quote = '[quote]19[\quote] This is a reply to the quote.';

$get = '/([quote])([0-9])([\quote])/';

$id = '';

preg_match($get, $quote, $id);

echo $id[0];

不幸的是,這並沒有給我我想要的結果,我嘗試了很多變化,甚至嘗試了preg_replace ,希望可能會給我我所需要的東西,但是在大量閱讀了堆棧溢出后,我認為preg_match是必經之路。 我只是似乎無法得到我想要的是引號標簽之間的ID。

我對preg經驗充其量是有限的,我盡了最大的努力使preg工作,但不幸的是,這超出了我目前的知識,因此將不勝感激。

提示

  • []用作字符類定界符。
    從字面上看時,它們必須轉義\\ [,\\]。
    定義[0-9]的確切含義是:數字字符類。
  • (…)方括號包含結果組。
    如果希望提取[quote]和[\\ quote]之間的數字數據,則應將([0-9] *?)放在方括號中。 結果將在$ id [1](組#1)中。
  • [\\ quote]中的反斜杠“ \\”字符也必須轉義,因為它本身就是轉義字符:[\\\\\\\\ quote](4倍\\,因為它被解釋了兩次;我知道有點棘手)。
    順便說一句:也許[/ quote]是故意的; 這樣會更容易(?)

<?php
    $quote1 = '[quote]19[\quote] This is a reply to the quote.';
    $quote2 = '[quote]19[/quote] This is a reply to the quote.';
    // $get = '/\[quote\]([0-9].*?)\[\quote\]/';
    $get1 = '%\[quote\]([0-9]*?)\[\\\\quote\]%';
    $get2 = '%\[quote\]([0-9]*?)\[/quote\]%';
    $id = '';
    preg_match($get1, $quote1, $id);
    echo '$get1,$quote1 :: ' . $id[1] . '<br />';
    preg_match($get2, $quote2, $id);
    echo '$get2,$quote2 :: ' . $id[1] . '<br />';
?>

輸出:
$ get1,$ quote1 :: 19
$ get2,$ quote2 :: 19

正則表達式評論

    \[          # Match the character “[” literally
    quote       # Match the characters “quote” literally
    \]          # Match the character “]” literally
    (           # Match the regular expression below and capture its match into backreference number 1
       [0-9]       # Match a single character in the range between “0” and “9”
          *?          # Between zero and unlimited times, as few times as possible, expanding as needed (lazy)
    )
    \[          # Match the character “[” literally
        \\\\       # Match the character “\” literally
    quote       # Match the characters “quote” literally
    \]          # Match the character “]” literally

暫無
暫無

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

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