I am trying to write a function which will be checked the open bbcode tags and the close bbcode tags.

Here is what I have write so far:

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!";
     }
}

It doesn't work. What am I forgetting?

有帮助吗?

解决方案

Regex

What stands out most is your regex patterns are incorrect...

This:

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

Should be:

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

Which could be further improved:

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

The i is used to make it case insensitive in case you have tags like [QUOTE].

You don't need to escape forward slashes (/) because you're using # as a delimiter.

You don't need the third argument in the preg_match_all because you aren't doing anything with it and you're overwriting it anyway...

IF(..)

I also suggest that you use the following code structure

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

as opposed to if(...){...} if(...){...} if(...){...} if(...){...}

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top