Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg_match: nothing to repeat / no match

Tags:

regex

php

I am using this: if(!preg_match('/^+[0-9]$/', '+1234567'))

and am getting:

Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 1

any ideas why?


update: Now using this: if(!preg_match('/^\+[0-9]$/', '+1234567'))

and am getting no match.

any ideas why?

like image 677
Hailwood Avatar asked Jul 11 '10 12:07

Hailwood


People also ask

What does Preg_match mean?

preg_match() in PHP – this function is used to perform pattern matching in PHP on a string. It returns true if a match is found and false if a match is not found. preg_split() in PHP – this function is used to perform a pattern match on a string and then split the results into a numeric array.

What is the difference between Preg_match and Preg_match_all?

preg_match stops looking after the first match. preg_match_all , on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.

What value is return by Preg_match?

Return Values ¶ preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information.


1 Answers

+ is a special character that indicates 1 or more of the previous character, and by not escaping it you are applying it to the caret. escape it with \ and it will match a literal plus sign.

if(!preg_match('/^\+[0-9]$/', '+1234567'))

EDIT:

The reason why it didn't match is because you specified 1 digit from 0-9 and the end of the string with $. You need to make it a variable amount of digits.

if(!preg_match('/^\+[0-9]+$/', '+1234567')) {

Shorter version:

if(!preg_match('/^\+\d+$/', '+1234567')) {
like image 114
meder omuraliev Avatar answered Sep 18 '22 14:09

meder omuraliev