使用php preg_match从论坛报价中获取id

时间:2016-01-27 12:08:56

标签: php forum quote

我一直在使用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的体验充其量是有限的,我已尽力尝试让它发挥作用但不幸的是,这超出了我目前的知识,所以任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

提示

  • [] 用作字符类分隔符。
    必须对它们进行转义\ [,\]才能从字面上理解。
    定义[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

Regex评论

    \[          # 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