mirza
mirza

Reputation: 5793

What's the difference between "*" and "?" in php preg match?

Is there a difference between using "*" or "?" in php preg_match ? or Is there an example ?

<?php

// the string to match against
$string = 'The cat sat on the matthew';

// matches the letter "a" followed by zero or more "t" characters
echo preg_match("/at*/", $string);

// matches the letter "a" followed by a "t" character that may or may not be present
echo preg_match("/at?/", $string);

Upvotes: 2

Views: 2884

Answers (2)

Alnitak
Alnitak

Reputation: 340055

* matches 0 or more

? matches 0 or 1

In the context of your particular tests you can't tell the difference because the * and ? matches aren't anchored or don't have anything following them - they'll both match any string that contains an a, whether followed by a t or not.

The difference matters if you had something after the match character, e.g.:

echo preg_match("/at*z/", "attz"); // true
echo preg_match("/at?z/", "attz"); // false - too many "t"s

whereas with yours:

echo preg_match("/at*/", "attz"); // true - 0 or more
echo preg_match("/at?/", "attz"); // true - but it stopped after the
                                  // first "t" and ignored the second

Upvotes: 7

JohnFx
JohnFx

Reputation: 34917

// matches the letter "a" followed by zero or more "t" characters

// matches the letter "a" followed by a "t" character that may or may not be present

source: You

Upvotes: 3

Related Questions