2

I am new to regex, and as i have studied, the * matches zero or more and + matches one or more, so i started to test this:

<?php
preg_match("/a/", 'bbba',$m);
preg_match("/a*/", 'bbba',$o);
preg_match("/a+/", 'bbba',$p);
echo '<pre>';
    var_dump($m);
    var_dump($o);
    var_dump($p);
echo '</pre>';  
?>

but the result is that * didn't match any thing and returned empty while the letter a exists:

array(1) {
  [0]=>
  string(1) "a"
}
array(1) {
  [0]=>
  string(0) ""
}
array(1) {
  [0]=>
  string(1) "a"
}

so what i miss here.

Gurmanjot Singh
  • 8,936
  • 2
  • 17
  • 37
Mohamed Omar
  • 395
  • 2
  • 16

3 Answers3

4

/a/ matches the first a in bbba

/a*/ matches 0 or more a characters. There are 0 a characters between the start of the string and the first b so it matches there.

/a+/ matches 1 or more a characters so it matches the first a character

The thing to note here is that a regex will try and match as early in the string it is checking as possible.

JGNI
  • 3,524
  • 9
  • 19
  • This is 'lazy' behavior. There is a good explanation for this behavior with regard to regular expressions [here][1]. [1]: https://stackoverflow.com/questions/2301285/what-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions – James Sheils Jan 28 '19 at 09:46
2

* means that the preceding item will be matched zero or more times.

+ means that the preceding item will be matched one or more times.

Also a* match empty, that why it shows an empty result. You can use preg_match_all("/a*/", 'bbba',$o); and then filter the results on the non-empty values of the array resulting.

Islam Elshobokshy
  • 8,788
  • 6
  • 20
  • 45
2

a* means match string which may NOT contain a because * matches zero or more,
hence pattern a* will match even empty string. To see all matches you can use preg_match_all, like:

<?php
preg_match_all("/a*/", 'bbba', $o);
var_dump($o);

as result you will see:

array(1) {
  [0]=>
  array(5) {
    [0]=>
    string(0) ""
    [1]=>
    string(0) ""
    [2]=>
    string(0) ""
    [3]=>
    string(1) "a"
    [4]=>
    string(0) ""
  }
}

hope it will help you.

cn007b
  • 14,506
  • 6
  • 48
  • 62