473,383 Members | 1,879 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

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($phone,$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_replace('-','',$phone);
$phone=str_replace('(','',$phone);
$phone=str_replace(')','',$phone);
$phone=str_replace(' ','',$phone);

if(!preg_match('/[\d]{'.$min.',}/',$phone)){
return(FALSE);
} else {
return(TRUE);
}
}
Jul 17 '05 #1
8 6959
.oO(gsv2com)
//is there a more direct approach to just count the amount of numbers in
the string by pattern matching?
$phone=str_replace('-','',$phone);
$phone=str_replace('(','',$phone);
$phone=str_replace(')','',$phone);
$phone=str_replace(' ','',$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($phone, $area = TRUE) {
$min = $area ? 10 : 7;
return strlen(str_replace(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($phone,$area='y'){
if($area=='y'){
$min=10;
} else {
$min=7;
}
// remove any non-digit from the string
$phone=preg_replace('/[^0-9]/','',$phone);

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

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

check_phone($phone,0);

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

--
Justin Koivisto - ju****@koivi.com
http://www.koivi.com
Jul 17 '05 #4
ch***********@hotmail.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_replace('/[^\d]/','',$phone);

Then simply compare the length of the string.

--
Justin Koivisto - ju****@koivi.com
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($phone,$area=TRUE){
$min = $area ? 10 : 7;
$phone=preg_replace('/[^0-9]/','',$phone);
return (strlen($phone)==$min)? TRUE : FALSE;
}

Very nice. Thanks again.
Jul 17 '05 #6
.oO(gsv2com)
function check_phone($phone,$area=TRUE){
$min = $area ? 10 : 7;
$phone=preg_replace('/[^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($phone,$area=TRUE){
$min = $area ? 10 : 7;
$phone=preg_replace('/[^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.com
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
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...
176
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? ...
2
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...
10
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,...
5
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...
9
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...
2
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...
19
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...
9
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.