tags:

views:

1410

answers:

4

The code below gives me this mysterious error, and i cannot fathom it. I am new to regular expressions and so am consequently stumped. The regular expression should be validating any international phone number.

Any help would be much appreciated.

function validate_phone($phone)
{
 $phoneregexp ="^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$";

 $phonevalid = 0;

 if (ereg($phoneregexp, $phone))
 {
  $phonevalid = 1;
 }else{
  $phonevalid = 0;
 }
}
+1  A: 

If this is PHP, then the regex must be enclosed in quotes. Furthermore, what's preg? Did you mean preg_match?

Another thing. PHP knows boolean values. The canonical solution would rather look like this:

return preg_match($regex, $phone) !== 0;

EDIT: Or, using ereg:

return ereg($regex, $phone) !== FALSE;

(Here, the explicit test against FALSE isn't strictly necessary but since ereg returns a number upon success I feel safer coercing the value into a bool).

Konrad Rudolph
maybe he's using ereg()?
Vinko Vrsalovic
@Vinko: Right. I was sure I had read `preg`. Damn. Still, since POSIX regular expressions are more or less deprecated, don't use these unless there's a tangible advantage.
Konrad Rudolph
You read it right, it was edited... :)
Vinko Vrsalovic
+2  A: 

Hmm well the code you pasted isn't quite valid, I fixed it up by adding the missing quotes, missing delimiters, and changed preg to preg_match. I didn't get the warning.

Edit: after seeing the other comment, you meant "ereg" not "preg"... that gives the warning. Try using preg_match() instead ;)

<?php
function validate_phone($phone)
{
        $phoneregexp ='/^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$/';

        $phonevalid = 0;

        if (preg_match($phoneregexp, $phone))
        {
                $phonevalid = 1;
        }else{
                $phonevalid = 0;
        }
}

validate_phone("123456");
?>
MrZebra
I'd, at the very least, return $phonevalid
Vinko Vrsalovic
Vrinko - I suspect the OP may have simplified the code they pasted, the return probably got lost in the process. The warning is the main problem, they can probably figure out what they want to return ;)
MrZebra
A: 

Just to provide some reference material please read

or if you'd like to stick with the POSIX regexp:

The correct sample code has already been given above.

Stefan Gehrig
A: 

It's the [0-9\\- ] part of your RE - it's not escaping the "-" properly. Change it to [0-9 -] and you should be OK (a "-" at the last position in a character class is treated as literal, not part of a range specification).

Greg