0

我正在尝试编写一个函数,它将检查打开的 bbcode 标记和关闭的 bbcode 标记。

这是我到目前为止所写的:

public function CheckBBCodes($argText)
{   
     $openQuoteTagCounter = preg_match_all('[quote]', $argText, $openQuoteTagCounter);
     $closeQuoteTagCounter = preg_match_all('#\[\/quote\]\s*#', $argText, $closeQuoteTagCounter);
     if($openQuoteTagCounter > $closeQuoteTagCounter)
     {
          echo "There are more open quote tags than close quote tags!";
     }
     if($closeQuoteTagCounter > $openQuoteTagCounter)
     {
          echo "There are more close quote tags than open quote tags!";
     }
}

它不起作用。我忘记了什么?

4

1 回答 1

0

正则表达式

最突出的是您的正则表达式模式不正确......

这个:

$openQuoteTagCounter  = preg_match_all('[quote]', $argText, $openQuoteTagCounter);
$closeQuoteTagCounter = preg_match_all('#\[\/quote\]\s*#', $argText, $closeQuoteTagCounter);

应该:

$openQuoteTagCounter  = preg_match_all('#\[quote\]#i', $argText, $openQuoteTagCounter);
$closeQuoteTagCounter = preg_match_all('#\[/quote\]#i', $argText, $closeQuoteTagCounter);

可以进一步改进的地方:

$openQuoteTagCounter  = preg_match_all('#\[quote\]#i', $argText);
$closeQuoteTagCounter = preg_match_all('#\[/quote\]#i', $argText);

i用于使其不区分大小写,以防您有[QUOTE].

您不需要转义正斜杠 ( /),因为您将#其用作分隔符。

您不需要在中的第三个参数,preg_match_all因为您没有对它做任何事情,并且无论如何您都在覆盖它......

如果(..)

我还建议您使用以下代码结构

if(X > Y){
    //Do stuff...
}
else if(Y > X){
    //Do other stuff...
}
else{
    //Do different stuff...
}

if(...){...} if(...){...} if(...){...} if(...){...}

于 2013-09-27T20:42:05.997 回答