0

I was reading the online manual of the preg_match function and wrote up a piece of code to test it. Along with it I wrote up another piece of code using preg_grep.

Here is the code:

$subject = array("Robert");
$subject2 = "Robert";
$pattern = "/./";


$result = preg_grep($pattern, $subject);
$result2 = preg_match($pattern, $subject2, $matches);
echo "<pre>";
print_r($result);
print_r($matches);
echo "</pre>";

For the preg_grep I got what I expected, an array element[0] with the value "Robert", that made sense.

For preg_match I got an unexpected result, at least to my understanding of regexp. It was an array element[0] with the value "R".

Why is that?

2 Answers 2

3

. matches any character except new line. So it would return first character since + isn't present.

Sign up to request clarification or add additional context in comments.

Comments

2

Because /./ means one character, not all. You should use a quantifier:

  • * means 0 or more characters
  • + means 1 or more characters
  • ? means 0 or 1 character

If you suffix quantifiers with ? it means an ungreedy match (which means that it tries to match as less characters as possible, and not as much characters as possible).

A complete result:

Input string: 'Robert'

Regex    Result
=====    ======

/.*/     Robert
/.*?/    null
/.+/     Robert
/.+?/    R
/.?/     R
/.??/    null

Comments

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.