RE: Seemingly weird regex problem

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, 2005-01-20 at 15:13, Michael Sims wrote:
> Tim Boring wrote:
> > On Thu, 2005-01-20 at 13:41, Jason Wong wrote:
> >> I suspect what you want to be doing is something like this:
> >>
> >>   switch (TRUE) {
> >>     case ANY_EXPRESSION_THAT_EVALUATES_TO_TRUE:
> >>     ...
> >>   }
> >
> > Thanks for the suggestion, but I'm not sure that does what I'm looking
> > for.  I really think the problem is with my regex, not necessarily
> > with the way I've constructed my switch statement.
> 
> No, Jason is right.  Your problem IS in the switch statement.  You cannot use it the
> way you are trying to and get the results you're expecting.  Each case expression is
> evaluated with the switch expression just as if you compared them with the "=="
> operator.  In your case, you're comparing the return value of preg_match() against
> the $line string.  This isn't what you want.
> 
> Here's what happens.  Say your $line contains the string "AKRN".  Your regex pattern
> matches only if the line begins with a non-word character.  "A" is definitely a word
> character, so the pattern does not match.  preg_match returns an integer indicating
> the number of matches, which in this case is 0.
> 
> To evaluate your case, PHP does the equivalent of:
> 
> if ("AKRN..." == 0)
> 
> which is actually TRUE.  From:
> 
> http://www.php.net/manual/en/language.types.string.php#language.types.string.convers
> ion
> 
> "If the string starts with valid numeric data, this will be the value used.
> Otherwise, the value will be 0 (zero)."
> 
> Since "AKRN" doesn't begin with valid numeric data, it is converted to 0 for the
> purposes of the comparison.  Since 0 == 0 the case comparison evaluates to true.
> 
> When you switch it to begin with a number, PHP now uses that number.  Say you switch
> it to "1AKRN".  PHP then will compare 1 == 0 which is false.
> 
> To accomplish what you want you'll have to change it to:
> 
> switch (true) {
>   case ($total_counter <= 5):
>     ...
>   case (preg_match(...):
>     ...
> 
> etc. as Jason suggested.  Why don't you try it and see if it works?
> 
> HTH

I tried it and it worked as Jason explained.  Sorry, I'm a little 
slow at times.  Thanks for taking the time and effort to explain 
this in more detail!

Tim

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux