Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Regex (different result between + and * )

Tags:

regex

php

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.

like image 396
JorgeeFG Avatar asked May 30 '13 13:05

JorgeeFG


People also ask

What is the difference between and * in regex?

* means zero-or-more, and + means one-or-more. So the difference is that the empty string would match the second expression but not the first.

What does W * mean in regex?

In regex, the uppercase metacharacter denotes the inverse of the lowercase counterpart, for example, \w for word character and \W for non-word character; \d for digit and \D or non-digit.

What does \+ mean in regex?

Example: "a\+" matches "a+" and not a series of one or "a"s. ^ the caret is the anchor for the start of the string, or the negation symbol. Example: "^a" matches "a" at the start of the string. Example: "[^0-9]" matches any non digit.

What is \r and \n in regex?

\n. Matches a newline character. \r. Matches a carriage return character.


1 Answers

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

like image 58
Casimir et Hippolyte Avatar answered Sep 20 '22 06:09

Casimir et Hippolyte