【发布时间】:2015-05-04 14:02:57
【问题描述】:
我正在尝试使用正则表达式解析 BBCode 报价。我的报价有一些变量,我想将它们存储在 PHP 变量中,以便稍后在代码中使用它们。
我的 BBCode 报价如下所示:
[quote=user;post_id] TEXT [/quote]
我的 PHP 代码:
function parseQuote($text) {
$pattern = '/\[quote=(.*?);(.*?)\](.*?)\[\/quote\]/'; // quote regex
preg_match($pattern, $text, $match );
$quote_text = $match[3]; // get the text
$replace = '
<blockquote class="posttext-blockquote">
<div class="posttext-blockquote-top">
<i class="fa fa-caret-up"></i> $1 said:
</div>
<div class="posttext-blockquote-bottom">
'.$quote_text.'...
</div>
</blockquote>'; // make the replace text, $quote_text will be used to check things later
return preg_replace($pattern,$replace,$text); // return parsed
}
我面临的问题是,即使 $match 数组中填充了数据,它仍然给我Notice: Undefined offset: 3 警告,但在我的网页上,它确实给了我报价文本。
当我执行print_r($match) 时,它会给我这个:
Array ( [0] => [quote=poepjejan1;15]Why can't I be a piggy :([/quote] [1] => poepjejan1 [2] => 15 [3] => Why can't I be a piggy :( ) 1
我尝试了各种方法,但它一直给我未定义的偏移错误。我在这里做错了什么?
附:我是正则表达式的新手。
【问题讨论】:
-
在 IDEONE 上,没有警告:ideone.com/Ej7Pxm
-
尝试你自己的错误处理程序,看看错误到底在哪里,如stackoverflow.com/a/5373824/3882707
-
@Ionut 是的,我刚刚发现我忘了添加错误处理程序,不过谢谢你告诉我:)
-
顺便说一句,你可能最好使用
/\[quote=(.+?);(\d+?)\](.+?)\[\/quote\]/i(demo 和比较your current)
标签: php arrays regex preg-replace preg-match