JorgeeFG
JorgeeFG

Reputation: 5961

PHP Regex (different result between + and * )

If I put * in my regex, it doesn't work, if I put +, it works.

* should mean 0 or more, + should mean 1 or more.


Case with *

$num = '    527545855   ';
var_dump( preg_match( '/\d*/', substr( $num, 0, 18 ), $coincidencias ) );
var_dump($coincidencias);exit;

Result:

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

Case with +

$num = '    527545855   ';
var_dump( preg_match( '/\d+/', substr( $num, 0, 18 ), $coincidencias ) );
var_dump($coincidencias);exit;

Result:

int(1)
array(1) {
  [0]=>
  string(9) "527545855"
}

I thought both should work, but I don't understand why the * doesn't work.

Upvotes: 5

Views: 134

Answers (5)

Anirudha
Anirudha

Reputation: 32797

It would match the digits or nothing

\d* means match 0 to many digits


For Example in

hello 123

the regex \d*

would match 8 times i.e 1 at start(^) ,6 times for hello and 1 time for 123

Upvotes: 3

Walls
Walls

Reputation: 4010

The * in a regex takes the character before it and looks for 0 or more instances. The + in a regex looks for 1 or more instances.

Since you aren't really checking around the number (caring for other items) you will get more items back from the regex with * since it allows for the 0 instance clause to be met, which is valid for all your spaces before the number (a space is matching 0 instances of a number). The + ensures at least one is found.

Upvotes: 2

gpojd
gpojd

Reputation: 23065

You answered this in your question:

* should mean 0 or more, + should mean 1 or more.

The first thing that it matched was 0 or more digits.

Upvotes: 4

nhahtdh
nhahtdh

Reputation: 56809

The engine will attempting to match starting from index 0.

  • Since \d* can match an empty string, the engine will return the empty string at index 0.
  • In contrast, \d+ must match at least one digit, and since the quantifier is greedy, it will return the nearest sequence of digits, while taking as many digits as possible (in your case, it is the whole sequence of digits in the input string).

Upvotes: 4

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

* means 0 or more occurences thus the first occurence is the void string in your test string

Upvotes: 7

Related Questions