Forum Moderators: coopster

Message Too Old, No Replies

preg match() problem

displays "Unknown Modifier '['"

         

dbarasuk

1:35 pm on Apr 6, 2008 (gmt 0)

10+ Year Member



Hi!

I have a text field containing a phone number that needs to be tested against a pattern

The form number is of the form (0032)499/78 98 34 and the pattern i designed looks like this:

if(array_key_exists('submit', $_POST))
{
// check phone number
$phone=trim($_POST['phone']);
if(!preg_match('/^([0-9]{4})[0-9]{3}/[0-9]{2}\h[0-9]{2}\h[0-9]{2}$/', $phone))

{
echo "Phone number does not appear to be valid";
include('../mysql_queries/display_form.inc.php');
exit();
}
When that script is run I get an error of the form:
Warning: preg_match() [function.preg-match]: Unknown modifier '[' in C:\htdocs\MySQL_queries\changephone.php on line 14
Does this phone number match the pattern?
Can you please tell me what's wrong with this code?
regards,

cameraman

4:57 pm on Apr 6, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



if(!preg_match('/^([0-9]{4})[0-9]{3}/[0-9]{2}\h[0-9]{2}\h[0-9]{2}$/', $phone))

Escape it:
if(!preg_match('/^([0-9]{4})[0-9]{3}\/[0-9]{2}\h[0-9]{2}\h[0-9]{2}$/', $phone))

dbarasuk

12:11 am on Apr 7, 2008 (gmt 0)

10+ Year Member



When escaped, the error notice is solved, but wonder why the phone number given above or here (0032)499/78 98 34 does not match that pattern namely '/^([0-9]{4})[0-9]{3}/[0-9]{2}\h[0-9]{2}\h[0-9]{2}$/'.

It's echoeing: "Phone number does not seem valid". I am confused at this point cause i thought the number matched the pattern that way. Any idea why this?

PHP_Chimp

5:55 pm on Apr 7, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Remember that ()'s are special characters in a regular expression, as they group things together. So if you want literal ()'s then you need to escape those as well.

if(!preg_match('/^[b]\[/b]([0-9]{4}[b]\[/b])[0-9]{3}\/[0-9]{2}\h[0-9]{2}\h[0-9]{2}$/', $phone));

dbarasuk

12:02 am on Apr 8, 2008 (gmt 0)

10+ Year Member



You're right!
doing what you said solved the problem.
tks!