Page 1 of 1

preg_match using OR or AND ?

Posted: Wed Nov 03, 2010 1:16 pm
by cc4digital
Does anyone know if you can use two variables in preg_match.
The code below seems to fail if I use both variables.

Code: Select all

<?php
//declaring variables
$f_name="chuck"; $l_name="bob";
//Validation of first name and last name looking for special symbols and numbers
if (!preg_match('/[a-zA-Z]/', $l_name|| $f_name))
{
	echo "Your name must be only alpha numberic characters A-Z or a-z.";
}
?>

Re: preg_match using OR or AND ?

Posted: Wed Nov 03, 2010 2:15 pm
by AbraCadaver
The same way you always concatenate things in PHP:

Code: Select all

if(!preg_match('/[a-zA-Z]/', $l_name.$f_name))
But I don't think that's what you want. That will display the error only if there are no letters. I think you want if there are other than letters? Maybe this:

Code: Select all

if(preg_match('/[^a-zA-Z]/', $l_name.$f_name))

Re: preg_match using OR or AND ?

Posted: Wed Nov 03, 2010 5:03 pm
by requinix
AbraCadaver's suggestion works in this situation because of what you're doing and with what data. In general, if you want to do something with two variables you need to repeat yourself:

Code: Select all

if(preg_match('/[^a-zA-Z]/', $l_name) || preg_match('/[^a-zA-Z]/', $f_name))
If all you want to allow is letters, don't use a regular expression for it - there are better functions available.

Re: preg_match using OR or AND ?

Posted: Thu Nov 04, 2010 1:32 am
by cc4digital
Thanks for the feedback--

AbraCadaver--Yep, I see. Never thought about concat.

tasairis --Yes, this was actually what I was thinking. It make sense to do it this way. I just thought the fuction could read the OR without the repeat.

Thank you both for you feedback. :drunk:

Re: preg_match using OR or AND ?

Posted: Thu Nov 04, 2010 1:35 am
by cc4digital
Learned something new every day. Never knew about this one--
ctype_alpha

Thanks tasairis :teach: