0

I started having hands with regular expressions in PHP and stuck in start.

I have written following block:-

$object = "ng_amg_gt-1";

switch ($object)
{
    case preg_match('/^ng_amg_gt-[0-9]+$/', $object):
        echo 'first';    
        break;

    case preg_match('/^ng_amg_gt-_cg-[0-9]+$/', $object):
        echo 'second';
        break;

}

I thought "ng_amg_gt-1" will match preg_match('/^ng_amg_gt-[0-9]+$/', $object) but interestingly(anoyingly) it is echoing second.

What I am missing?

PS :- It may seem an obvious question but not getting any breakthrough, thats why I have posted it over here.

Thanks

3
  • 2
    preg_match returns an int, you're doing a switch on a string, and I dont even know if that's valid. Just do an if (preg_match(...)) Commented May 25, 2012 at 18:26
  • oh NO, I did a blunder, Apologies Commented May 25, 2012 at 18:29
  • Have look at stackoverflow.com/a/4046018/372239 Commented May 26, 2012 at 10:28

2 Answers 2

2

What I am missing?

Here is what you missed:

$object = "ng_amg_gt-1";

if(preg_match('/^ng_amg_gt-[0-9]+$/', $object)) {
    echo 'first';
} else if(preg_match('/^ng_amg_gt-_cg-[0-9]+$/', $object)) {
    echo 'second';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the efforts, I got an idea from this
1

preg_match returns the number of pattern matches and you compare that to a string

1 Comment

I offer mea-culpa for this blunder

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.