preg_match using OR or AND ?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cc4digital
Forum Newbie
Posts: 9
Joined: Wed Nov 03, 2010 1:09 pm

preg_match using OR or AND ?

Post 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.";
}
?>
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: preg_match using OR or AND ?

Post 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))
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: preg_match using OR or AND ?

Post 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.
Last edited by requinix on Thu Nov 04, 2010 6:14 am, edited 1 time in total.
cc4digital
Forum Newbie
Posts: 9
Joined: Wed Nov 03, 2010 1:09 pm

Re: preg_match using OR or AND ?

Post 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:
cc4digital
Forum Newbie
Posts: 9
Joined: Wed Nov 03, 2010 1:09 pm

Re: preg_match using OR or AND ?

Post by cc4digital »

Learned something new every day. Never knew about this one--
ctype_alpha

Thanks tasairis :teach:
Post Reply