ZCE Exam Question: Which PCRE regular expression will match the string PhP5-rocks?

Which PCRE regular expression will match the string PhP5-rocks?

Answer…

[ ]

/^[hp1-5]*\-.*/i

[ ]

/[hp1-5]*\-.?/

[ ]

/[hp][1-5]*\-.*/

[ ]

/[PhP]{3}[1-5]{2,3}\-.*$/

[ ]

/[a-z1-5\-]*/

I got intrigued with this question. At first it seems too easy, but it requires a little understanding from PHP’s PCRE functions to really understand it.

If you do the following code and execute it:

<?php

$string = 'PhP5-rocks';

print_r(preg_match(‘/^[hp1-5]*\-.*/i’,$string,$matches,PREG_OFFSET_CAPTURE));
print_r($matches);

print_r(preg_match(‘/[hp1-5]*\-.?/’,$string,$matches,PREG_OFFSET_CAPTURE));
print_r($matches)

print_r(preg_match(‘/[hp][1-5]*\-.*/’,$string,$matches,PREG_OFFSET_CAPTURE));
print_r($matches);

print_r(preg_match(‘/[PhP]{3}[1-5]{2,3}\-.*$/’,$string,$matches,PREG_OFFSET_CAPTURE));
print_r($matches);

print_r(preg_match(‘/[a-z1-5\-]*/’,$string,$matches,PREG_OFFSET_CAPTURE));
print_r($matches);
?>

The first, second and last print_r will print 1 at the screen and the remaining will print 0. If you read preg_match function manual you will see that preg_match returns 1 or 0 always, being 1 as it has matched a string that matches that regex that was given to test. Considering this, you would have 3 correct answers for this puzzle but, in fact there’s only one. When you add the refereced parameter $matches and print it, you will see that the only regex that matches the string is the first one.

When I first have answered this question, I have answered wrongly. I did missed the fact that were a capital P on the string (well who knew…), but this helped me to see what’s was wrong and seek for the correct answer.

I will keep you guys posted. More to come with PHP 5 and Zend Certifications.

Advertisements

About mcloide

Making things simpler, just check: http://www.mcloide.com View all posts by mcloide

2 responses to “ZCE Exam Question: Which PCRE regular expression will match the string PhP5-rocks?

  • jhOy imPeRiaL

    i am really having a hard time studying regular expression. i am self studying for a month now for 2 hours a day. hope ill get to understand this now.

  • mcloide

    I used to have a lot of issues studying REGEX, but as soon as I started to work with Apache Rewrite Rules, Everything became a bit clear. Try to place some REGEX in everyday examples and it became a bit clear of how it works. Remember, REGEX is nothing else besides logic. Good luck.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: