我正在尝试编写一个函数,它将检查open bbcode标签和close 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!";
}
}
它不起作用。我忘记了什么?
答案 0 :(得分: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(...){...}