473,756 Members | 5,156 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PHP Pattern Matching - Is there a better solution?

One of my weaknesses has always been pattern matching. Something I
definitely need to study up on and maybe you guys can give me a pointer
here.

I'm looking to remove all of this code and just use pattern matching to
determine if the proper amount of numeric characters has been met. Here is
the function I've already done. Any help you can give in a pattern matching
solution would be much appreciated and very educational.
//the $area option is for determining if the user need (or need not) type in
their area code.

function check_phone($ph one,$area='y'){
if($area=='y'){
$min=10;
} else {
$min=7;
}

//is there a more direct approach to just count the amount of numbers in
the string by pattern matching?
$phone=str_repl ace('-','',$phone);
$phone=str_repl ace('(','',$pho ne);
$phone=str_repl ace(')','',$pho ne);
$phone=str_repl ace(' ','',$phone);

if(!preg_match( '/[\d]{'.$min.',}/',$phone)){
return(FALSE);
} else {
return(TRUE);
}
}
Jul 17 '05 #1
8 6980
.oO(gsv2com)
//is there a more direct approach to just count the amount of numbers in
the string by pattern matching?
$phone=str_repl ace('-','',$phone);
$phone=str_repl ace('(','',$pho ne);
$phone=str_repl ace(')','',$pho ne);
$phone=str_repl ace(' ','',$phone);

if(!preg_match( '/[\d]{'.$min.',}/',$phone)){
return(FALSE);
} else {
return(TRUE);
}
}


I would simply remove all the special chars and then check the length of
the remaining string, no need for pattern matching here:

function check_phone($ph one, $area = TRUE) {
$min = $area ? 10 : 7;
return strlen(str_repl ace(array('-', '(', ')', ' '), '', $phone)) >= $min;
}

HTH
Micha
Jul 17 '05 #2
Regular expression is definitely something that's worth spending the
time mastering. In this case it's not strictly necessary. But for more
complex validation, it'll makes your life a whole lot easier.

Here's the pattern, built in pieces for educational purpose:

$pattern = '';

// the beginning of the string
$pattern .= '^';

// 0 or more white spaces (just in case)
$pattern .= '\s*';
if($area) {
// optional open paren
$pattern .= '\(?';

// capturing 3 digits
$pattern .= '(\d{3})';

// optional close paren
$pattern .= '\)';

// optional dash, or space
$pattern .= '[\- ]?';
}

// capturing next 3 digits
$pattern .= '(\d{3})';

// optional dash or space
$pattern .= '[\- ]?';

// capturing 4 digits
$pattern .= '(\d{4})';

// 0 or more white spaces
$pattern .= '\s*';

// end of string
$pattern .= '$';

// altogether >> '^\s*\(?(\d{3}) \)?[\- ]?(\d{3})[\- ]?(\d{4})\s*$'
if(preg_match("/$pattern/", $phone, $matches)) {
...
}

Jul 17 '05 #3
gsv2com wrote:
One of my weaknesses has always been pattern matching. Something I
definitely need to study up on and maybe you guys can give me a pointer
here.

I'm looking to remove all of this code and just use pattern matching to
determine if the proper amount of numeric characters has been met. Here is
the function I've already done. Any help you can give in a pattern matching
solution would be much appreciated and very educational.


function check_phone($ph one,$area='y'){
if($area=='y'){
$min=10;
} else {
$min=7;
}
// remove any non-digit from the string
$phone=preg_rep lace('/[^0-9]/','',$phone);

return (strlen($phone) ==$min)? TRUE : FALSE;
}

Just be careful what you pass for the $area value. If you call:

check_phone($ph one,0);

You *will* need the area code. (string to int conversion in if statement).

--
Justin Koivisto - ju****@koivi.co m
http://www.koivi.com
Jul 17 '05 #4
ch***********@h otmail.com wrote:
Regular expression is definitely something that's worth spending the
time mastering. In this case it's not strictly necessary. But for more
complex validation, it'll makes your life a whole lot easier.

Here's the pattern, built in pieces for educational purpose:

$pattern = '';

// the beginning of the string
$pattern .= '^';

// 0 or more white spaces (just in case)
$pattern .= '\s*';
if($area) {
// optional open paren
$pattern .= '\(?';

// capturing 3 digits
$pattern .= '(\d{3})';

// optional close paren
$pattern .= '\)';
That isn't optional... this is ;)
$pattern .= '\)?';
// optional dash, or space
$pattern .= '[\- ]?';
}

// capturing next 3 digits
$pattern .= '(\d{3})';

// optional dash or space
$pattern .= '[\- ]?';

// capturing 4 digits
$pattern .= '(\d{4})';

// 0 or more white spaces
$pattern .= '\s*';

// end of string
$pattern .= '$';

// altogether >> '^\s*\(?(\d{3}) \)?[\- ]?(\d{3})[\- ]?(\d{4})\s*$'
if(preg_match("/$pattern/", $phone, $matches)) {
...
}


Hmm.. might want to make that a bit more generic. I've seen users
delimit phone number parts with characters other than a - or space (like
a dot, long hyphen, comma, etc.).

Maybe better would be something like this:

^[^\d]*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4})[^\d]*$

Of course, you could just remove all the non-digits:
$phone=preg_rep lace('/[^\d]/','',$phone);

Then simply compare the length of the string.

--
Justin Koivisto - ju****@koivi.co m
http://www.koivi.com
Jul 17 '05 #5
Thanks for your help guys. As the end result, I used a combination of a few
of your tips to make the finalized function:

function check_phone($ph one,$area=TRUE) {
$min = $area ? 10 : 7;
$phone=preg_rep lace('/[^0-9]/','',$phone);
return (strlen($phone) ==$min)? TRUE : FALSE;
}

Very nice. Thanks again.
Jul 17 '05 #6
.oO(gsv2com)
function check_phone($ph one,$area=TRUE) {
$min = $area ? 10 : 7;
$phone=preg_rep lace('/[^0-9]/','',$phone);
return (strlen($phone) ==$min)? TRUE : FALSE;
}


JFTR: It's not necessary to explicitly return TRUE or FALSE in this
case. It's redundant because the result of the comparision will already
be of type boolean:

return strlen($phone) == $min;

does the same without another unnecessary operation.

In the preg_replace() pattern you could also use the character class \d
(digits) instead of 0-9:

'/[^\d]/'

And another thing: Are you sure the numbers will always exactly be 7 or
10 digits long? At least here in Germany the length of phone numbers may
vary. That's why I used >= instead of == in my example and your first
code also suggested that.

Micha
Jul 17 '05 #7
Michael Fesser wrote:
.oO(gsv2com)

function check_phone($ph one,$area=TRUE) {
$min = $area ? 10 : 7;
$phone=preg_rep lace('/[^0-9]/','',$phone);
return (strlen($phone) ==$min)? TRUE : FALSE;
}


JFTR: It's not necessary to explicitly return TRUE or FALSE in this
case. It's redundant because the result of the comparision will already
be of type boolean:

return strlen($phone) == $min;

does the same without another unnecessary operation.


I usually include the explicit returns just for readability sake. ;)

--
Justin Koivisto - ju****@koivi.co m
http://www.koivi.com
Jul 17 '05 #8
gsv2com wrote:
One of my weaknesses has always been pattern matching.


<snip>

Perhaps you should try <http://www.weitz.de/regex-coach/>

--
<?php echo 'Just another PHP saint'; ?>
Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com/

Jul 17 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3800
by: NimP | last post by:
Hi,. I'm trying to detect any links that are contained within an html page using eregi pattern matching. I was wondering if there are any pattern matching geniuses out there who could write a pattern that merges all the different manners in which a link could be wriiten, Current patterns I can think of include: <a href=x.com> no spaces betwen href, equals and url, no quotation marks around url <a href =x.com> space between href and...
176
8169
by: Thomas Reichelt | last post by:
Moin, short question: is there any language combining the syntax, flexibility and great programming experience of Python with static typing? Is there a project to add static typing to Python? Thank you, -- greetz tom
2
5057
by: ahogue at theory dot lcs dot mit dot edu | last post by:
Hello - Is there any way to match complex subtree patterns with XPath? The functions I see all seem to match along a single path from root to leaf. I would like to match full subtrees. For example, given the XHTML: <html> <body>
10
4983
by: bpontius | last post by:
The GES Algorithm A Surprisingly Simple Algorithm for Parallel Pattern Matching "Partially because the best algorithms presented in the literature are difficult to understand and to implement, knowledge of fast and practical algorithms is not commonplace." Hume and Sunday, "Fast String Searching", Software - Practice and Experience, Vol. 21 # 11, pp 1221-48
5
5758
by: olaufr | last post by:
Hi, I'd need to perform simple pattern matching within a string using a list of possible patterns. For example, I want to know if the substring starting at position n matches any of the string I have a list, as below: sentence = "the color is $red" patterns = pos = sentence.find($)
9
5067
by: Jim Lewis | last post by:
Anyone have experience with string pattern matching? I need a fast way to match variables to strings. Example: string - variables ============ abcaaab - xyz abca - xy eeabcac - vxw x matches abc
2
3398
by: Ole Nielsby | last post by:
First, bear with my xpost. This goes to comp.lang.c++ comp.lang.functional with follow-up to comp.lang.c++ - I want to discuss an aspect of using C++ to implement a functional language, and I'd like the attention of fp as well as C++ gurus if available. The language I'm implementing - PILS - is dynamically
19
3178
by: konrad Krupa | last post by:
I'm not expert in Pattern Matching and it would take me a while to come up with the syntax for what I'm trying to do. I hope there are some experts that can help me. I'm trying to match /d/d/d/s/d/d in any text. There could be spaces in front or after the pattern (the nnn nn could be without spaces also) but it shouldn't pick it up in case like this 1234 56768
9
4319
by: Chris | last post by:
Is anyone aware of any prior work done with searching or matching a pattern over nested Python lists? I have this problem where I have a list like: , 9, 9], 10] and I'd like to search for the pattern so that is returns: , 9, 9], 10] , 9, 9]
0
9462
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9287
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10046
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9886
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9857
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9722
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7259
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5318
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3369
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.