FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » CTYPE
Show: Today's Messages :: Polls :: Message Navigator
Switch to threaded view of this topic Create a new topic Submit Reply
CTYPE [message #182663] Sun, 25 August 2013 17:51 Go to next message
bill is currently offline  bill
Messages: 310
Registered: October 2010
Karma: 0
Senior Member
Hi all,

I'm still working on the postal code issue, for Canada at the moment and
I'm still stuck.

I've decided to try:
= See if it's alpha-numeric
= Create an array
= See if there is a space where it belongs
= Validate for digits in proper positions
= Since it's alpha-numeric, the 3 characters left must be Alphabetic.
If the validations work, keep going.
If not, halt & allow for a re-entry.

The ctype statement will NOT work in any form and throws various errors
regardless of wher I place it or what I use s the var. Remove the entire
ctype, and everything works again.

In code, this equates to, as best as I can:
--------------------------------------------------------------------------- ------------------------
IF(strlen($zip) === 7) {
echo "Zip appears to be Canadian . <br />";
}
// ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC

* if (ctype_alnum(str_split($zip,1)) { <---- Throws error [1]
* echo "Is Alpha Numeric.";
*}

// ================ LET'S ASSIGN IT TO AN ARRAY
echo ' <pre>';
print_r(str_split($zip,1));
echo '</pre>';

// ================= check space where it belongs
if($zip[3] === " ") {
echo "Space in correct place<br />";
}
--------------------------------------------------------------------------- ----------------------

[1] : Error is:
Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\twa1.php on
line 107
Line 107 is:
echo "Zip appears to be Canadian . <br />";
--------------------------------------------------------------------------- ----------------------
I have tried various forms of the ctype statement, where it's shown here
and lower in the code after the array is generated, and using $zip[0] .
$zip[3]... etc. I simply can not get any form of the ctype statement
working and I have a LOT of sample code I've collected from several
sources, all not quite what I need.
--------------------------------------------------------------------------- ----------------------

If I change the code & location as follows:
IF(strlen($zip) === 7) {
echo "Zip appears to be Canadian . <br />";
}
// ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC

// ================ LET'S ASSIGN IT TO AN ARRAY
echo ' <pre>';
print_r(str_split($zip,1)); <--------------- LINE 114
echo '</pre>';

if (ctype_alnum(($zip[0]))
echo "Is Alpha Numeric.";

// ================= check space where it belongs
if($zip[3] === " ") {
echo "Space in correct place<br />";
}
--------------------------------------------------------------------------- ------------------
It still throws an error as:
Parse error: syntax error, unexpected T_ECHO in C:\xampp\htdocs\twa1.php
on line 114


What the heck am I doing wrong? Any advice appreciated; I can't believe
I can't get ctype to work; it seems so simple!

TIA,

Twayne`
Re: CTYPE [message #182664 is a reply to message #182663] Sun, 25 August 2013 18:21 Go to previous messageGo to next message
Richard Yates is currently offline  Richard Yates
Messages: 86
Registered: September 2013
Karma: 0
Member
On Sun, 25 Aug 2013 13:51:14 -0400, Twayne <nobody(at)spamcop(dot)net> wrote:

> if (ctype_alnum(str_split($zip,1)) { <---- Throws error [1]

After a previous thread in which several people pointed out your
unbalanced parens, followed by suggestions about how you might
systematically discover such elementary errors, followed by
discussions about editors that could point these out and in which YOU
yourself recommended one that does this,

how is it that you are still posting code like this?
Re: CTYPE [message #182665 is a reply to message #182663] Sun, 25 August 2013 18:38 Go to previous messageGo to next message
J.O. Aho is currently offline  J.O. Aho
Messages: 194
Registered: September 2010
Karma: 0
Senior Member
On 25/08/13 19:51, Twayne wrote:
> Hi all,
>
> I'm still working on the postal code issue, for Canada at the moment and
> I'm still stuck.
>
> I've decided to try:
> = See if it's alpha-numeric
> = Create an array
> = See if there is a space where it belongs
> = Validate for digits in proper positions
> = Since it's alpha-numeric, the 3 characters left must be Alphabetic.
> If the validations work, keep going.
> If not, halt & allow for a re-entry.
>
> The ctype statement will NOT work in any form and throws various errors
> regardless of wher I place it or what I use s the var. Remove the entire
> ctype, and everything works again.
>
> In code, this equates to, as best as I can:
> --------------------------------------------------------------------------- ------------------------
>
> IF(strlen($zip) === 7) {
> echo "Zip appears to be Canadian . <br />";
> }
> // ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC
>
> * if (ctype_alnum(str_split($zip,1)) { <---- Throws error [1]
> * echo "Is Alpha Numeric.";
> *}

I assume you have just added the '*' first in the line to show which
rows you are talking about.

Simple maths will show your error, lets count your opening parentheses

if (ctype_alnum(str_split($zip,1)) {
1 2 3

and now the number of closing parentheses

if (ctype_alnum(str_split($zip,1)) {
12

So we get 3 opening parenthesis and 2 closing, this is what the "Parse
error: syntax error, unexpected '{'" is about, you need to close all
your parentheses.


You know you will end up with loads of if cases if you keep on doing
this instead of using a regular expression, this would speed it up and
make your code a lot easier to read (case insensitive):


if(preg_match("/^[a-z]\d[a-z] \d[a-z]\d$/i",$postcode)) {
// this could be a valid Canadian postcode
// just add what you need to do to check it against
// Canadian Post, worst case use the "Find a post office"
}


--

//Aho
Re: CTYPE [message #182666 is a reply to message #182664] Sun, 25 August 2013 19:00 Go to previous messageGo to next message
bill is currently offline  bill
Messages: 310
Registered: October 2010
Karma: 0
Senior Member
On 2013-08-25 2:21 PM, Richard Yates wrote:
> On Sun, 25 Aug 2013 13:51:14 -0400, Twayne <nobody(at)spamcop(dot)net> wrote:
>
>> if (ctype_alnum(str_split($zip,1)) { <---- Throws error [1]
>
> After a previous thread in which several people pointed out your
> unbalanced parens, followed by suggestions about how you might
> systematically discover such elementary errors, followed by
> discussions about editors that could point these out and in which YOU
> yourself recommended one that does this,
>
> how is it that you are still posting code like this?
>

OmiGod, I didn't see that and looked over & over & ...!

Actually, I found the method I'm now using by perusing those old threads
and have managed it, finally.

I have nothing useful to contribute here, so ... that's what I'm doing.
Sorry if it irks you; but that's called "life". When one has nothing
useful to say, that's exactly what they should say: Nothing.
Re: CTYPE [message #182667 is a reply to message #182666] Sun, 25 August 2013 19:05 Go to previous messageGo to next message
Richard Yates is currently offline  Richard Yates
Messages: 86
Registered: September 2013
Karma: 0
Member
On Sun, 25 Aug 2013 15:00:19 -0400, Twayne <nobody(at)spamcop(dot)net> wrote:

> On 2013-08-25 2:21 PM, Richard Yates wrote:
>> On Sun, 25 Aug 2013 13:51:14 -0400, Twayne <nobody(at)spamcop(dot)net> wrote:
>>
>>> if (ctype_alnum(str_split($zip,1)) { <---- Throws error [1]
>>
>> After a previous thread in which several people pointed out your
>> unbalanced parens, followed by suggestions about how you might
>> systematically discover such elementary errors, followed by
>> discussions about editors that could point these out and in which YOU
>> yourself recommended one that does this,
>>
>> how is it that you are still posting code like this?
>>
> OmiGod, I didn't see that and looked over & over & ...!

Try this:

<?php
function TwaynesParens($mycode) {
$leftparens=substr_count($mycode,'(');
$rightparens=substr_count($mycode, ')');
if($leftparens==$rightparens) {
echo '<br />Good for me! The problem is not unblanced
parens in my code (for once.)';
} else {
echo '<br />I did it again.<br />DO NOT POST THIS CODE
TO COMP.LANG.PHP!';
}
}
$mycode='(()()';
TwaynesParens($mycode);
?>
Re: CTYPE [message #182668 is a reply to message #182663] Sun, 25 August 2013 19:11 Go to previous messageGo to next message
Norman Peelman is currently offline  Norman Peelman
Messages: 126
Registered: September 2010
Karma: 0
Senior Member
On 08/25/2013 01:51 PM, Twayne wrote:
> Hi all,
>
> I'm still working on the postal code issue, for Canada at the moment and
> I'm still stuck.
>
> I've decided to try:
> = See if it's alpha-numeric
> = Create an array
> = See if there is a space where it belongs
> = Validate for digits in proper positions
> = Since it's alpha-numeric, the 3 characters left must be Alphabetic.
> If the validations work, keep going.
> If not, halt & allow for a re-entry.
>
> The ctype statement will NOT work in any form and throws various errors
> regardless of wher I place it or what I use s the var. Remove the entire
> ctype, and everything works again.
>
> In code, this equates to, as best as I can:
> --------------------------------------------------------------------------- ------------------------
>
> IF(strlen($zip) === 7) {
> echo "Zip appears to be Canadian . <br />";
> }
> // ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC
>
> * if (ctype_alnum(str_split($zip,1)) { <---- Throws error [1]
> * echo "Is Alpha Numeric.";
> *}
>
> // ================ LET'S ASSIGN IT TO AN ARRAY
> echo ' <pre>';
> print_r(str_split($zip,1));
> echo '</pre>';
>
> // ================= check space where it belongs
> if($zip[3] === " ") {
> echo "Space in correct place<br />";
> }
> --------------------------------------------------------------------------- ----------------------
>
>
> [1] : Error is:
> Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\twa1.php on
> line 107
> Line 107 is:
> echo "Zip appears to be Canadian . <br />";
> --------------------------------------------------------------------------- ----------------------
>
> I have tried various forms of the ctype statement, where it's shown here
> and lower in the code after the array is generated, and using $zip[0] .
> $zip[3]... etc. I simply can not get any form of the ctype statement
> working and I have a LOT of sample code I've collected from several
> sources, all not quite what I need.
> --------------------------------------------------------------------------- ----------------------
>
>
> If I change the code & location as follows:
> IF(strlen($zip) === 7) {
> echo "Zip appears to be Canadian . <br />";
> }
> // ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC
>
> // ================ LET'S ASSIGN IT TO AN ARRAY
> echo ' <pre>';
> print_r(str_split($zip,1)); <--------------- LINE 114
> echo '</pre>';
>
> if (ctype_alnum(($zip[0]))
> echo "Is Alpha Numeric.";
>
> // ================= check space where it belongs
> if($zip[3] === " ") {
> echo "Space in correct place<br />";
> }
> --------------------------------------------------------------------------- ------------------
>
> It still throws an error as:
> Parse error: syntax error, unexpected T_ECHO in C:\xampp\htdocs\twa1.php
> on line 114
>
>
> What the heck am I doing wrong? Any advice appreciated; I can't believe
> I can't get ctype to work; it seems so simple!
>
> TIA,
>
> Twayne`
>
>

I don't understand why you're not using the regex that does away with
all that code.

$canadian_regex =
"/([A-CEG-HJ-NPR-TVXY]{1}[0-9]{1})[A-CEG-HJ-NPR-TVXY]{1}
{1}([0-9]{1}[A-CEG-HJ-NPR-TVXY]{1}[0-9]{1})/";
$zip = "A2B 3X4";

IF (preg_match($canadian_regex,$zip)) {
echo "Zip is Canadian\n";
} else {
echo "Zip is not Canadian\n";
}

--------
or
--------


$usa_regex = "/[0-9]{5}(-{0,1}[0-9]{4}){0,1}/";
$canadian_regex =
"/([A-CEG-HJ-NPR-TVXY]{1}[0-9]{1})[A-CEG-HJ-NPR-TVXY]{1}
{1}([0-9]{1}[A-CEG-HJ-NPR-TVXY]{1}[0-9]{1})/";

....

$isUSA = (preg_match($usa_regex,$zip)) ? TRUE : FALSE;
$isCanadian = (preg_match($canadian_regex,$zip)) ? TRUE : FALSE;


--------
or
--------

// by country ISO

$postal_code['US'] = "/[0-9]{5}(-{0,1}[0-9]{4}){0,1}/";
$postal_code['CA'] =
"/([A-CEG-HJ-NPR-TVXY]{1}[0-9]{1})[A-CEG-HJ-NPR-TVXY]{1}
{1}([0-9]{1}[A-CEG-HJ-NPR-TVXY]{1}[0-9]{1})/";
$postal_code['VI'] = "/008[0-5]{1}1/";

$isUSA = (preg_match($postal_code['US'],$zip)) ? TRUE : FALSE;
$isCanadian = (preg_match($postal_code['CA'],$zip)) ? TRUE : FALSE;
$isVirginIslands = (preg_match($postal_code['VI'],$zip)) ? TRUE : FALSE;

etc.

--
Norman
Registered Linux user #461062
-Have you been to www.php.net yet?-
Re: CTYPE [message #182669 is a reply to message #182665] Sun, 25 August 2013 19:28 Go to previous messageGo to next message
bill is currently offline  bill
Messages: 310
Registered: October 2010
Karma: 0
Senior Member
On 2013-08-25 2:38 PM, J.O. Aho wrote:
> On 25/08/13 19:51, Twayne wrote:
>> Hi all,
>>
>> I'm still working on the postal code issue, for Canada at the moment and
>> I'm still stuck.
>>
>> I've decided to try:
>> = See if it's alpha-numeric
>> = Create an array
>> = See if there is a space where it belongs
>> = Validate for digits in proper positions
>> = Since it's alpha-numeric, the 3 characters left must be
>> Alphabetic.
>> If the validations work, keep going.
>> If not, halt & allow for a re-entry.
>>
>> The ctype statement will NOT work in any form and throws various errors
>> regardless of wher I place it or what I use s the var. Remove the entire
>> ctype, and everything works again.
>>
>> In code, this equates to, as best as I can:
>> --------------------------------------------------------------------------- ------------------------
>>
>>
>> IF(strlen($zip) === 7) {
>> echo "Zip appears to be Canadian . <br />";
>> }
>> // ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC
>>
>> * if (ctype_alnum(str_split($zip,1)) { <---- Throws error [1]
>> * echo "Is Alpha Numeric.";
>> *}
>
> I assume you have just added the '*' first in the line to show which
> rows you are talking about.

Correct.

>
> Simple maths will show your error, lets count your opening parentheses
>
> if (ctype_alnum(str_split($zip,1)) {
> 1 2 3

So Richard noted also. I even fired up another editor that shows parens
et al by simply hoering a mouse over the tag. Damned if I didn't see it
there either!
>
> and now the number of closing parentheses
>
> if (ctype_alnum(str_split($zip,1)) {
> 12
>
> So we get 3 opening parenthesis and 2 closing, this is what the "Parse
> error: syntax error, unexpected '{'" is about, you need to close all
> your parentheses.

It's so clearly visible to me now; no idea why I couldn't see it before.
>
>
> You know you will end up with loads of if cases if you keep on doing
> this instead of using a regular expression, this would speed it up and
> make your code a lot easier to read (case insensitive):
>
>
> if(preg_match("/^[a-z]\d[a-z] \d[a-z]\d$/i",$postcode)) {
> // this could be a valid Canadian postcode
> // just add what you need to do to check it against
> // Canadian Post, worst case use the "Find a post office"
> }
>
>

I agree with you but I'm not useing regular expressions. 1 they're never
clear to me, 2 I'm trying to avoid them as I have a couple in other
cases where they actually cause noticeable slow-downs on even my Local
Server, and magnitudes worse with I upload them to be "live", 3 there
are so many ways to do the same thing in PHP my goal is to learn them
and take notes of the most useful.
So it's not just learning to code properly, it's also to learn
better, less-code ways of doing things.

If you're so inclined you won't miss anything if you don't read the
following but it might be well to explain a couple of things about the
real reasons I'm having so much trouble here.

Mainly, I've been disabled and "retired" since 1994. In 2002 I suffered
a serious brain concussion and lost many memories plus any ability w/r
to Short Term Memory. I was even labeled "learning impaired" due to the
concussion. My doctor advised me that I might be able to get some of my
old memories back, along with kicking the "learning disabled" tag, by
"exercising" my brain. He suggested since I liked computers that I find
a way to use them to exercise the ol' gray matter.
Currently I've regained most of my old memories and an no longer
considered "learning disabled", but handling short-term memory issues is
a real fight. IFF I handle them properly, I am able to retain memories,
but it's often thwarted by not remembering to take the notes I need or
otherwise record the information. That, on top of my disabilities (3
types of arthritis, several myalgias and other sundry things, make it
hard. So, when I thought I was ready a few months ago, I decided to
take on either VB net again, or PHP, both of which I knew at one point
in time. I chose PHP because I did have some websites to my credit, and
used a lot of old PHP code (well it's old now), so my overall goals now
are to get to know PHP well enough to use it and also participate with
responses on groups and forums such as this one. And besides, VB code
is expensive <g> since I was unable to work.

I don't give up easily and "Patience and Perseverence" is my mantra
these days. It actually works! lol

I dislike saying all those things about myself, but I think it's fair to
mention them as part of my gratitude for this group and several others.

Regards,

Twayne`
Re: CTYPE THREAD RESOLVED [message #182670 is a reply to message #182663] Sun, 25 August 2013 19:35 Go to previous messageGo to next message
bill is currently offline  bill
Messages: 310
Registered: October 2010
Karma: 0
Senior Member
If anyone is interested, here's the code I ended up with. It still
needs to validate alphabetic & numeric array positions but that should
be reasonably simple to add by checking the array positions for alpha or
digit characters.

Thanks for all the help!
-----------------------------------
$zip = check_input($zip);
$zip = strtoupper($zip);
// DETERMINE IF US POSTAL CODE
if(strlen($zip)===5) {
echo "U.S. postal code used "; }
IF (is_numeric($zip)) {
echo " and is 5 digits.";
}
IF(strlen($zip) === 7) {
echo "Zip appears to be Canadian . <br />";
}
// ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC

// ================ LET'S ASSIGN IT TO AN ARRAY
echo ' <pre>';
print_r(str_split($zip,1));
echo '</pre>';

// ================= check space is where it belongs
if($zip[3] === " ") {
echo "<br />Space in correct place<br />";
}

$sUser = $zip;
$aValid = array(' ');
if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
echo "Username has a problem";
echo 'Your Postal Code is NOT properly formatted.';
}
else {
echo "Postal code is properly formatted as ALPHA NUMERIC with ONE SPACE
as the 4th character";
}
Re: CTYPE [message #182671 is a reply to message #182669] Sun, 25 August 2013 20:16 Go to previous messageGo to next message
Richard Yates is currently offline  Richard Yates
Messages: 86
Registered: September 2013
Karma: 0
Member
On Sun, 25 Aug 2013 15:28:00 -0400, Twayne <nobody(at)spamcop(dot)net> wrote:

> Currently I've regained most of my old memories and an no longer
> considered "learning disabled", but handling short-term memory issues is
> a real fight. IFF I handle them properly, I am able to retain memories,
> but it's often thwarted by not remembering to take the notes I need or
> otherwise record the information.

For things that come up repeatedly, posting a short reminder can be
helpful. I have taped to my monitor a note that says '=' !== '=='
Re: CTYPE [message #182672 is a reply to message #182669] Sun, 25 August 2013 20:19 Go to previous messageGo to next message
Christoph Michael Bec is currently offline  Christoph Michael Bec
Messages: 207
Registered: June 2013
Karma: 0
Senior Member
Twayne wrote:

> On 2013-08-25 2:38 PM, J.O. Aho wrote:
>> On 25/08/13 19:51, Twayne wrote:
>>
>> Simple maths will show your error, lets count your opening parentheses
>>
>> if (ctype_alnum(str_split($zip,1)) {
>> 1 2 3
>
> So Richard noted also. I even fired up another editor that shows parens
> et al by simply hoering a mouse over the tag. Damned if I didn't see it
> there either!

If you're having problems keeping *nesting* parens balanced, you might
consider to avoid them. The code above could be written this way:

$characters = str_split($zip, 1);
$is_alphanumeric = ctype_alnum($characters);
if ($is_aphanumeric)
{

This has the additional advantage that it eases debugging.

BTW: The code won't work, as ctype_alnum() expects a string, but
str_split() returns an array.

--
Christoph M. Becker
Re: CTYPE [message #182673 is a reply to message #182669] Sun, 25 August 2013 20:42 Go to previous messageGo to next message
Fiver is currently offline  Fiver
Messages: 35
Registered: July 2013
Karma: 0
Member
On 2013-08-25 21:28, Twayne wrote:
> On 2013-08-25 2:38 PM, J.O. Aho wrote:
>> You know you will end up with loads of if cases if you keep on doing
>> this instead of using a regular expression, this would speed it up and
>> make your code a lot easier to read (case insensitive):
>>
>> if(preg_match("/^[a-z]\d[a-z] \d[a-z]\d$/i",$postcode)) {
>> // this could be a valid Canadian postcode
>> // just add what you need to do to check it against
>> // Canadian Post, worst case use the "Find a post office"
>> }

> I agree with you but I'm not useing regular expressions. 1 they're never
> clear to me, 2 I'm trying to avoid them as I have a couple in other
> cases where they actually cause noticeable slow-downs on even my Local
> Server, and magnitudes worse with I upload them to be "live", 3 there
> are so many ways to do the same thing in PHP my goal is to learn them
> and take notes of the most useful.
> So it's not just learning to code properly, it's also to learn
> better, less-code ways of doing things.

Your original question was answered, but it seems you have a few
misconceptions about regular expressions. If you into learning how to do
things properly, you shouldn't dismiss them out of hand.

ad 1) "they're never clear to me"

That's a fair point, as regexes can quickly become hard to read. There's
a way around that, however: the /x modifier. Take for example the regex
in the post you replied to (just as an example, I'm not judging its
correctness for now):

preg_match("/^[a-z]\d[a-z] \d[a-z]\d$/i", $postcode)

This can also be written as

$regex = '/
^ # anchored at the start of the string
[a-z] # one letter a-z
\d # one digit 0-9
[a-z] # one letter a-z
\s # one character of white space *
\d # one digit 0-9
[a-z] # one letter a-z
\d # one digit 0-9
$ # anchored at the end of the string
/ix';

preg_match($regex, $postcode)

Much easier to understand this way, especially if you're starting out
with regular expressions. That's all one string - all the white space
and the comments are ignored. (Talking about white space, a more exact
way to match "one space character" would be "[ ]").

ad 2) "they're too slow"

That may have been true in other languages and many, many years ago, but
it's certainly not the case with PHP today. This regex runs over 2
million times per second on a single core of my middle-aged laptop. It
should be more than fast enough, considering I could check every
Canadian's zip code in under 15 seconds with it... I don't know what
you're building, but I can guarantee that this won't be the reason for
any noticeable slow-downs.

ad 3) "there are many other ways"

True, but the regex is by far the shortest. It's also what most
programmers would expect to see in this situation. It is, as you say, a
"better, less-code" way to do it.

[snip]

> I dislike saying all those things about myself

I found it interesting to read.

regards,
5er
Re: CTYPE [message #182674 is a reply to message #182668] Sun, 25 August 2013 22:04 Go to previous messageGo to next message
Tim Streater is currently offline  Tim Streater
Messages: 328
Registered: September 2010
Karma: 0
Senior Member
In article <kvdktm$ejb$1(at)dont-email(dot)me>,
Norman Peelman <npeelman(at)cfl(dot)rr(dot)com> wrote:


> I don't understand why you're not using the regex that does away with
> all that code.
>
> $canadian_regex =
> "/([A-CEG-HJ-NPR-TVXY]{1}[0-9]{1})[A-CEG-HJ-NPR-TVXY]{1}
> {1}([0-9]{1}[A-CEG-HJ-NPR-TVXY]{1}[0-9]{1})/";

Personally I avoid regexps like the plague as they tend to be
write-only. My take is that if I'd wanted to do line-noise, I'd be using
TECO as an editor instead of TextWrangler.

--
Tim

"That excessive bail ought not to be required, nor excessive fines imposed,
nor cruel and unusual punishments inflicted" -- Bill of Rights 1689
Re: CTYPE [message #182675 is a reply to message #182673] Mon, 26 August 2013 08:25 Go to previous messageGo to next message
Thomas 'PointedEars'  is currently offline  Thomas 'PointedEars'
Messages: 701
Registered: October 2010
Karma: 0
Senior Member
Fiver wrote:

> Your original question was answered, but it seems you have a few
> misconceptions about regular expressions. If you into learning how to do
> things properly, you shouldn't dismiss them out of hand.
>
> ad 1) "they're never clear to me"
>
> That's a fair point, as regexes can quickly become hard to read. There's
> a way around that, however: the /x modifier. Take for example the regex
> in the post you replied to (just as an example, I'm not judging its
> correctness for now):
>
> preg_match("/^[a-z]\d[a-z] \d[a-z]\d$/i", $postcode)
>
> This can also be written as
>
> $regex = '/
> ^ # anchored at the start of the string
> [a-z] # one letter a-z
> \d # one digit 0-9
> [a-z] # one letter a-z
> \s # one character of white space *
> \d # one digit 0-9
> [a-z] # one letter a-z
> \d # one digit 0-9
> $ # anchored at the end of the string
> /ix';
>
> preg_match($regex, $postcode)

JFTR: This applies to *Perl* and *Perl-compatible* regular expressions
(PCRE) only. PHP also supports POSIX Extended REGular expressions (ERE)
that do not have that feature. However, the POSIX ERE functions (ereg*())
are deprecated since PHP 5.3 in favor of the PCRE functions (preg_*()).

PHP also supports commenting in PCRE like so:

$regex = '/'
. '^(?# anchored at the start of the string)'
. '[a-z](?# one letter a-z)'
. '\\d(?# one digit 0-9)'
. '[a-z](?# one letter a-z)'
. '\\s(?# one character of white space)'
. '\\d(?# one digit 0-9)'
. '[a-z](?# one letter a-z)'
. '\\d(?# one digit 0-9)'
. '$(?# anchored at the end of the string)
. '/ix';

<http://php.net/manual/en/regexp.reference.comments.php>

(In this case, I would pick the PCRE_EXTENDED variant, too. “(?#…)” is
better suited for short inline comments.)


Another way, which can be combined with either one, is to use another
delimiter. For example, attempting to match an “http:” URI with

'/http:\\/\\/(?:[^\\/\\s]+)\\/?/'

is safe, but rather hard to read. It can be written better readable as

'#http://(?:[^/\\s]+)/?#'

or, with PCRE_EXTENDED enabled,

'! http:// (?:[^/\\s]+) /? !x'

This can be further simplified to

'! http:// (?: .+?) /? !x'

and even inline-commented as suggested above (“#” changed to “!” because of
unescaped “#” delimiting single-line inline comments).

> […] a more exact way to match "one space character" would be "[ ]").

Or simply " ". The character class has the slight advantage over the simple
assertion that it does not matter how many spaces you write between the
brackets. However, character class building might prove to be more
expensive than the simple assertion, and even if it looks as if there are
only spaces in-between, a tab character or another non-breaking whitespace
character could have slipped in – a bug waiting to happen that is easily
spotted with the simple assertion (it just does not match then).

> ad 2) "they're too slow"
>
> That may have been true in other languages and many, many years ago, but
> it's certainly not the case with PHP today. This regex runs over 2
> million times per second on a single core of my middle-aged laptop. It
> should be more than fast enough, considering I could check every
> Canadian's zip code in under 15 seconds with it... I don't know what
> you're building, but I can guarantee that this won't be the reason for
> any noticeable slow-downs.

It is still true that regular expressions are (or can be) comparably
expensive with regard to runtime and memory usage, which is why some (non-
PHP) runtime environments disable them by default for security reasons.
However, if you are using regular expressions for *pattern* matching, the
program will likely run faster than if you had used plain string operations.
Because the native machine code (of PHP) has been optimized for that
purpose.

(Rule of thumb: Explicitly prevent regular expressions from becoming too
greedy even though in the end they would not match more than they should.
And do not capture what you do not want to process. It is *unnecessary*
backtracking and capturing that makes regular expressions more expensive
than they could be.)

For example,

preg_match('/foo/', 'foobar') > 0

has no advantage over

strpos('foobar', 'foo') !== false

But

preg_match('/\\bfoo/u', 'foobar') > 0

has as it matches “foo” only at the *start* of a *Unicode* word.

It should also be noted that (Perl-compatible) regular expressions are
included in one of the ten areas you need to be knowledgable in (“Strings &
Patterns”), in order to pass the Zend Certified Engineer PHP 5.3 test:

<http://www.zend.com/services/certification/php-5-certification/>


PointedEars
--
When all you know is jQuery, every problem looks $(olvable).
Re: CTYPE [message #182676 is a reply to message #182675] Mon, 26 August 2013 08:29 Go to previous messageGo to next message
The Natural Philosoph is currently offline  The Natural Philosoph
Messages: 993
Registered: September 2010
Karma: 0
Senior Member
On 26/08/13 09:25, Thomas 'PointedEars' Lahn wrote:
> It should also be noted that (Perl-compatible) regular expressions are
> included in one of the ten areas you need to be knowledgable in
> (“Strings & Patterns”), in order to pass the Zend Certified Engineer
> PHP 5.3 test:
> <http://www.zend.com/services/certification/php-5-certification/>
> PointedEars
I've been coding PHP for about 5years now and C/Unix/linux for over 30
and I have never ever found it worthwhile using complex regexps.

There is always a simpler way to do it.

--
Ineptocracy

(in-ep-toc’-ra-cy) – a system of government where the least capable to lead are elected by the least capable of producing, and where the members of society least likely to sustain themselves or succeed, are rewarded with goods and services paid for by the confiscated wealth of a diminishing number of producers.
Re: CTYPE [message #182677 is a reply to message #182671] Mon, 26 August 2013 15:49 Go to previous messageGo to next message
bill is currently offline  bill
Messages: 310
Registered: October 2010
Karma: 0
Senior Member
On 2013-08-25 4:16 PM, Richard Yates wrote:
> On Sun, 25 Aug 2013 15:28:00 -0400, Twayne <nobody(at)spamcop(dot)net> wrote:
>
>> Currently I've regained most of my old memories and an no longer
>> considered "learning disabled", but handling short-term memory issues is
>> a real fight. IFF I handle them properly, I am able to retain memories,
>> but it's often thwarted by not remembering to take the notes I need or
>> otherwise record the information.
>
> For things that come up repeatedly, posting a short reminder can be
> helpful. I have taped to my monitor a note that says '=' !== '=='
>

lol, I hear you there! I think I've been Post-It's major income! That's
actually why now I use NoteTab Pro; I have their PHP and SQL libraries
and clips, plus created my own abbreviated clip for often used
statements. They make it easy to create your own clip libraries. It has
a section for "learned" and one for "new" statements, both of which are
complete with formatting, such as:

A complete Form start set of code, with or without the html, body, div,
etc.
End form, body, html, and optionally <div> tags.
$ = check_input("$"); [one of several functions ]
/*
*/
<br />
"<br />"
.." <br />
$_SESSION[""]=$_POST[""];
autofocus = "autofocus"

to mention just a few of them at random.
They save a tremendous amount of typing for me, meaning less time to
forget something during the process of coding, even though I'm a
touch-typist, and I try hard to use a lot of comments.

Where I get in trouble is when I have to go back and edit for whatever
reason, and lose a parens or curly bracket in the process. And when I
get tired without realizing it I manage to compound those errors. e.g.
I'll add something that appears to work, and then a few tests later
added something where the earlier error became obvious.Fortunately I
like coding and am always after ways to help myself but ...

I also occasionally use NotePad++ too; it automatically displays tag
matching by just hovering the mouse over one.
Both NoteTab & NotePad++ know when a file they have open has been
modified and won't let you do anything until you tell it to reload or
keep what it has in memory. The two are competitively equal except
NotePad doesn't seem to have any capability to create libraries or code
clips.

I have other apps but none (yet) that come close to NoteTab Pro. IMO, at
least.

Cheers,

Twayne`
Re: CTYPE [message #182678 is a reply to message #182672] Mon, 26 August 2013 16:15 Go to previous messageGo to next message
bill is currently offline  bill
Messages: 310
Registered: October 2010
Karma: 0
Senior Member
On 2013-08-25 4:19 PM, Christoph Michael Becker wrote:
> Twayne wrote:
>
>> On 2013-08-25 2:38 PM, J.O. Aho wrote:
>>> On 25/08/13 19:51, Twayne wrote:
>>>
>>> Simple maths will show your error, lets count your opening parentheses
>>>
>>> if (ctype_alnum(str_split($zip,1)) {
>>> 1 2 3
>>
....
> If you're having problems keeping *nesting* parens balanced, you might
> consider to avoid them. The code above could be written this way:
>
> $characters = str_split($zip, 1);
> $is_alphanumeric = ctype_alnum($characters);
> if ($is_aphanumeric)
> {

Agreed & understood.
>
> This has the additional advantage that it eases debugging.
>
> BTW: The code won't work, as ctype_alnum() expects a string, but
> str_split() returns an array.
>

Wish my code snippet hadn't been snipped, because it did work, without
the parens issue.
$var was intended to be used in some places and $var[n] in others
but I don't.
That said, I'll have a relook again as you might have a point; alnum
still isn't giveing me what I need and I've assued it's been because of
a necessary space in the string, which I thought I'd taken proper care of.

Thanks for the prods.

Twayne`
Re: CTYPE [message #182679 is a reply to message #182676] Mon, 26 August 2013 16:37 Go to previous messageGo to next message
bill is currently offline  bill
Messages: 310
Registered: October 2010
Karma: 0
Senior Member
On 2013-08-26 4:29 AM, The Natural Philosopher wrote:
> On 26/08/13 09:25, Thomas 'PointedEars' Lahn wrote:
>> It should also be noted that (Perl-compatible) regular expressions are
>> included in one of the ten areas you need to be knowledgable in
>> (“Strings & Patterns”), in order to pass the Zend Certified Engineer
>> PHP 5.3 test:
>> <http://www.zend.com/services/certification/php-5-certification/>
>> PointedEars
> I've been coding PHP for about 5years now and C/Unix/linux for over 30
> and I have never ever found it worthwhile using complex regexps.
>
> There is always a simpler way to do it.
>

You, Fiver and Thomas all have strong backgrounds compared to mine, I'm
sure. It's not that I have an aversion to regex on any solid opinions of
my own, but a lot of material I've read and committed to disc, from both
aged and current opinions, suggest regex isn't the best way to go.
So I checked with my remote server support folks and they also wish a
lot of people would stop using regex type patterns as they're
time-intensive, more so than the alternatives. But at the same time they
say they'll never ask a customer to NOT use them as they have plenty of
cpu time available. So it wasn't exactly definitive, but at least they
did make the comments for me. oh; it was a phone call for what that's
worth, not support e-mail. I have several websites parked there too so I
get free extended support.

At any rate, since regex types are like learning another language for
me, I'm happy to rationalize that I'm doing the right thing by not using
them. Also, a lot of the newer things added to PHP's latest versions,
many seem to be aimed at being able to work without using regex type things.

Cheers,

Twayne`
Re: CTYPE THREAD RESOLVED [message #182680 is a reply to message #182670] Mon, 26 August 2013 18:07 Go to previous messageGo to next message
Fiver is currently offline  Fiver
Messages: 35
Registered: July 2013
Karma: 0
Member
On 2013-08-25 21:35, Twayne wrote:
> If anyone is interested, here's the code I ended up with. It still
> needs to validate alphabetic & numeric array positions but that should
> be reasonably simple to add by checking the array positions for alpha or
> digit characters.
>
> Thanks for all the help!
> -----------------------------------
> $zip = check_input($zip);
> $zip = strtoupper($zip);
> // DETERMINE IF US POSTAL CODE
> if(strlen($zip)===5) {
> echo "U.S. postal code used "; }
> IF (is_numeric($zip)) {
> echo " and is 5 digits.";
> }
> IF(strlen($zip) === 7) {
> echo "Zip appears to be Canadian . <br />";
> }
> // ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC
>
> // ================ LET'S ASSIGN IT TO AN ARRAY
> echo ' <pre>';
> print_r(str_split($zip,1));
> echo '</pre>';
>
> // ================= check space is where it belongs
> if($zip[3] === " ") {
> echo "<br />Space in correct place<br />";
> }
>
> $sUser = $zip;
> $aValid = array(' ');
> if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
> echo "Username has a problem";
> echo 'Your Postal Code is NOT properly formatted.';
> }
> else {
> echo "Postal code is properly formatted as ALPHA NUMERIC with ONE SPACE
> as the 4th character";
> }

For the US zip codes:

is_numeric() is not the correct function to use here. "+.1e1" and
"0xCAB" are both numeric strings and would pass as US zip codes.
Better solution:

if (strlen($zip) == 5 && ctype_digit($zip)) {
echo "looks like a US zip code\n";
}

Better yet: check for known bad zip codes as well

... && $zip != "00000" && $zip != "99999" && I don't know, some more

For the Canadian zip codes:

Your code has a comment "let's assign it to an array", and you also
wrote that you still needed to validate the array positions, but you
never do create an array (except for the unnecessary one in $aValid,
which should probably be a string).

Anyway, you're right that you still need to check the characters to the
right and left of the space, or strings like "x " and " 3 "
would be seen as valid zip codes. Here's one way to do it:

if (strlen($zip) == 7
&& $zip[3] == " "
&& ctype_alpha($zip[0] . $zip[2] . $zip[5])
&& ctype_digit($zip[1] . $zip[4] . $zip[6]))
{
echo "looks like a Canadian zip code\n";
}

Note the two closing parens after $zip[6] ;)


regards,
5er


PS: No regexes were killed or injured in the production of this message.
Re: CTYPE THREAD RESOLVED [message #182681 is a reply to message #182680] Mon, 26 August 2013 19:19 Go to previous messageGo to next message
The Natural Philosoph is currently offline  The Natural Philosoph
Messages: 993
Registered: September 2010
Karma: 0
Senior Member
On 26/08/13 19:07, Fiver wrote:
> On 2013-08-25 21:35, Twayne wrote:
>> If anyone is interested, here's the code I ended up with. It still
>> needs to validate alphabetic & numeric array positions but that should
>> be reasonably simple to add by checking the array positions for alpha or
>> digit characters.
>>
>> Thanks for all the help!
>> -----------------------------------
>> $zip = check_input($zip);
>> $zip = strtoupper($zip);
>> // DETERMINE IF US POSTAL CODE
>> if(strlen($zip)===5) {
>> echo "U.S. postal code used "; }
>> IF (is_numeric($zip)) {
>> echo " and is 5 digits.";
>> }
>> IF(strlen($zip) === 7) {
>> echo "Zip appears to be Canadian . <br />";
>> }
>> // ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC
>>
>> // ================ LET'S ASSIGN IT TO AN ARRAY
>> echo ' <pre>';
>> print_r(str_split($zip,1));
>> echo '</pre>';
>>
>> // ================= check space is where it belongs
>> if($zip[3] === " ") {
>> echo "<br />Space in correct place<br />";
>> }
>>
>> $sUser = $zip;
>> $aValid = array(' ');
>> if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
>> echo "Username has a problem";
>> echo 'Your Postal Code is NOT properly formatted.';
>> }
>> else {
>> echo "Postal code is properly formatted as ALPHA NUMERIC with ONE SPACE
>> as the 4th character";
>> }
> For the US zip codes:
>
> is_numeric() is not the correct function to use here. "+.1e1" and
> "0xCAB" are both numeric strings and would pass as US zip codes.
> Better solution:
>
> if (strlen($zip) == 5 && ctype_digit($zip)) {
> echo "looks like a US zip code\n";
> }
>
> Better yet: check for known bad zip codes as well
>
> ... && $zip != "00000" && $zip != "99999" && I don't know, some more
>
> For the Canadian zip codes:
>
> Your code has a comment "let's assign it to an array", and you also
> wrote that you still needed to validate the array positions, but you
> never do create an array (except for the unnecessary one in $aValid,
> which should probably be a string).
>
> Anyway, you're right that you still need to check the characters to the
> right and left of the space, or strings like "x " and " 3 "
> would be seen as valid zip codes. Here's one way to do it:
>
> if (strlen($zip) == 7
> && $zip[3] == " "
> && ctype_alpha($zip[0] . $zip[2] . $zip[5])
> && ctype_digit($zip[1] . $zip[4] . $zip[6]))
> {
> echo "looks like a Canadian zip code\n";
> }
>
> Note the two closing parens after $zip[6] ;)
>
>
> regards,
> 5er
>
>
> PS: No regexes were killed or injured in the production of this message.
>

Now key in SW1A 1AA as a postcode and see what it does with it.

there is a world beyond north America.

--
Ineptocracy

(in-ep-toc’-ra-cy) – a system of government where the least capable to lead are elected by the least capable of producing, and where the members of society least likely to sustain themselves or succeed, are rewarded with goods and services paid for by the confiscated wealth of a diminishing number of producers.
Re: CTYPE THREAD RESOLVED [message #182682 is a reply to message #182681] Mon, 26 August 2013 20:51 Go to previous messageGo to next message
Fiver is currently offline  Fiver
Messages: 35
Registered: July 2013
Karma: 0
Member
On 2013-08-26 21:19, The Natural Philosopher wrote:
> On 26/08/13 19:07, Fiver wrote:
>> For the Canadian zip codes:
[snip]
>> if (strlen($zip) == 7
>> && $zip[3] == " "
>> && ctype_alpha($zip[0] . $zip[2] . $zip[5])
>> && ctype_digit($zip[1] . $zip[4] . $zip[6]))
>> {
>> echo "looks like a Canadian zip code\n";
>> }
[snip]

> Now key in SW1A 1AA as a postcode and see what it does with it.

It won't be recognized as a Canadian zip code, which is as it should be.

> there is a world beyond north America.

Meh, that's just a rumor.
And even if there is, I heard that there be dragons.

The question was about US and Canadian zip codes, so what's your point?


regards,
5er
Re: CTYPE THREAD RESOLVED [message #182683 is a reply to message #182682] Mon, 26 August 2013 20:57 Go to previous messageGo to next message
Jerry Stuckle is currently offline  Jerry Stuckle
Messages: 2598
Registered: September 2010
Karma: 0
Senior Member
On 8/26/2013 4:51 PM, Fiver wrote:
> On 2013-08-26 21:19, The Natural Philosopher wrote:
>> On 26/08/13 19:07, Fiver wrote:
>>> For the Canadian zip codes:
> [snip]
>>> if (strlen($zip) == 7
>>> && $zip[3] == " "
>>> && ctype_alpha($zip[0] . $zip[2] . $zip[5])
>>> && ctype_digit($zip[1] . $zip[4] . $zip[6]))
>>> {
>>> echo "looks like a Canadian zip code\n";
>>> }
> [snip]
>
>> Now key in SW1A 1AA as a postcode and see what it does with it.
>
> It won't be recognized as a Canadian zip code, which is as it should be.
>
>> there is a world beyond north America.
>
> Meh, that's just a rumor.
> And even if there is, I heard that there be dragons.
>
> The question was about US and Canadian zip codes, so what's your point?
>
>
> regards,
> 5er
>

TNP just hates to be left out (of ANYTHING).


--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex(at)attglobal(dot)net
==================
Re: CTYPE THREAD RESOLVED [message #182684 is a reply to message #182682] Mon, 26 August 2013 21:07 Go to previous messageGo to next message
Tim Streater is currently offline  Tim Streater
Messages: 328
Registered: September 2010
Karma: 0
Senior Member
In article <kvgf5b$lfm$1(at)dont-email(dot)me>, Fiver <numeralfive(at)gmail(dot)com>
wrote:

> On 2013-08-26 21:19, The Natural Philosopher wrote:

>> there is a world beyond north America.
>
> Meh, that's just a rumor.
> And even if there is, I heard that there be dragons.
>
> The question was about US and Canadian zip codes, so what's your point?

I suspect it was that Canadians don't have zip codes.

--
Tim

"That excessive bail ought not to be required, nor excessive fines imposed,
nor cruel and unusual punishments inflicted" -- Bill of Rights 1689
Re: CTYPE THREAD RESOLVED [message #182685 is a reply to message #182680] Tue, 27 August 2013 21:18 Go to previous messageGo to next message
bill is currently offline  bill
Messages: 310
Registered: October 2010
Karma: 0
Senior Member
On 2013-08-26 2:07 PM, Fiver wrote:
> On 2013-08-25 21:35, Twayne wrote:
>> If anyone is interested, here's the code I ended up with. It still
>> needs to validate alphabetic & numeric array positions but that should
>> be reasonably simple to add by checking the array positions for alpha or
>> digit characters.
>>
>> Thanks for all the help!
>> -----------------------------------
>> $zip = check_input($zip);
>> $zip = strtoupper($zip);
>> // DETERMINE IF US POSTAL CODE
>> if(strlen($zip)===5) {
>> echo "U.S. postal code used "; }
>> IF (is_numeric($zip)) {
>> echo " and is 5 digits.";
>> }
>> IF(strlen($zip) === 7) {
>> echo "Zip appears to be Canadian . <br />";
>> }
>> // ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC
>>
>> // ================ LET'S ASSIGN IT TO AN ARRAY
>> echo ' <pre>';
>> print_r(str_split($zip,1));
>> echo '</pre>';
>>
>> // ================= check space is where it belongs
>> if($zip[3] === " ") {
>> echo "<br />Space in correct place<br />";
>> }
>>
>> $sUser = $zip;
>> $aValid = array(' ');
>> if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
>> echo "Username has a problem";
>> echo 'Your Postal Code is NOT properly formatted.';
>> }
>> else {
>> echo "Postal code is properly formatted as ALPHA NUMERIC with ONE SPACE
>> as the 4th character";
>> }
>
> For the US zip codes:
>
> is_numeric() is not the correct function to use here. "+.1e1" and
> "0xCAB" are both numeric strings and would pass as US zip codes.

OOPS! Good catch!

> Better solution:
>
> if (strlen($zip) == 5 && ctype_digit($zip)) {
> echo "looks like a US zip code\n";
> }
>
> Better yet: check for known bad zip codes as well

Good point.

>
> ... && $zip != "00000" && $zip != "99999" && I don't know, some more
>
> For the Canadian zip codes:
>
> Your code has a comment "let's assign it to an array", and you also
> wrote that you still needed to validate the array positions, but you
> never do create an array (except for the unnecessary one in $aValid,
> which should probably be a string).

Agreed; the original array code was removed at that point in the coding.

>
> Anyway, you're right that you still need to check the characters to the
> right and left of the space, or strings like "x " and " 3 "
> would be seen as valid zip codes. Here's one way to do it:
>
> if (strlen($zip) == 7
> && $zip[3] == " "
> && ctype_alpha($zip[0] . $zip[2] . $zip[5])
> && ctype_digit($zip[1] . $zip[4] . $zip[6]))
> {
> echo "looks like a Canadian zip code\n";
> }
>
> Note the two closing parens after $zip[6] ;)
>
>
> regards,
> 5er
....

Hmm, ALL great observations; thanks much.
I'll have a look at everything you mentioned here. It's much more
efficient than I've been putting together so far.

Regards,

Twayne`
Re: CTYPE THREAD RESOLVED [message #182686 is a reply to message #182683] Tue, 27 August 2013 21:20 Go to previous messageGo to next message
bill is currently offline  bill
Messages: 310
Registered: October 2010
Karma: 0
Senior Member
On 2013-08-26 4:57 PM, Jerry Stuckle wrote:

>
> TNP just hates to be left out (of ANYTHING).
>
>

Trolling again I see.
Re: CTYPE THREAD RESOLVED [message #182687 is a reply to message #182686] Tue, 27 August 2013 23:47 Go to previous messageGo to next message
Jerry Stuckle is currently offline  Jerry Stuckle
Messages: 2598
Registered: September 2010
Karma: 0
Senior Member
On 8/27/2013 5:20 PM, Twayne wrote:
> On 2013-08-26 4:57 PM, Jerry Stuckle wrote:
>
>>
>> TNP just hates to be left out (of ANYTHING).
>>
>>
>
> Trolling again I see.
>
>

ROFLMAO. And you said you plonked me. I knew you couldn't do it!


--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex(at)attglobal(dot)net
==================
Re: CTYPE THREAD RESOLVED [message #182688 is a reply to message #182681] Wed, 28 August 2013 12:49 Go to previous message
bill is currently offline  bill
Messages: 310
Registered: October 2010
Karma: 0
Senior Member
On 2013-08-26 3:19 PM, The Natural Philosopher wrote:
> On 26/08/13 19:07, Fiver wrote:
>> On 2013-08-25 21:35, Twayne wrote:
>>> If anyone is interested, here's the code I ended up with. It still
>>> needs to validate alphabetic & numeric array positions but that should
>>> be reasonably simple to add by checking the array positions for alpha or
>>> digit characters.
>>>
>>> Thanks for all the help!
....

>>> }
>>> IF(strlen($zip) === 7) {
>>> echo "Zip appears to be Canadian . <br />";
>>> }
>>> // ================== NOW LOOK TO SEE IF IT'S ALPHA-NUMERIC
>>>
>>> // ================ LET'S ASSIGN IT TO AN ARRAY
>>> echo ' <pre>';
>>> print_r(str_split($zip,1));
>>> echo '</pre>';
>>>
>>> // ================= check space is where it belongs
>>> if($zip[3] === " ") {
>>> echo "<br />Space in correct place<br />";
>>> }
>>>
>>> $sUser = $zip;
>>> $aValid = array(' ');
>>> if(!ctype_alnum(str_replace($aValid, '', $sUser))) {
>>> echo "Username has a problem";
>>> echo 'Your Postal Code is NOT properly formatted.';
>>> }
>>> else {
>>> echo "Postal code is properly formatted as ALPHA NUMERIC with ONE SPACE
>>> as the 4th character";
>>> }
>> For the US zip codes:
>>
>> is_numeric() is not the correct function to use here. "+.1e1" and
>> "0xCAB" are both numeric strings and would pass as US zip codes.
>> Better solution:
>>
>> if (strlen($zip) == 5 && ctype_digit($zip)) {
>> echo "looks like a US zip code\n";
>> }
>>
>> Better yet: check for known bad zip codes as well
>>
>> ... && $zip != "00000" && $zip != "99999" && I don't know, some more
>>
>> For the Canadian zip codes:
>>
>> Your code has a comment "let's assign it to an array", and you also
>> wrote that you still needed to validate the array positions, but you
>> never do create an array (except for the unnecessary one in $aValid,
>> which should probably be a string).
>>
>> Anyway, you're right that you still need to check the characters to the
>> right and left of the space, or strings like "x " and " 3 "
>> would be seen as valid zip codes. Here's one way to do it:
>>
>> if (strlen($zip) == 7
>> && $zip[3] == " "
>> && ctype_alpha($zip[0] . $zip[2] . $zip[5])
>> && ctype_digit($zip[1] . $zip[4] . $zip[6]))
>> {
>> echo "looks like a Canadian zip code\n";
>> }
>>
>> Note the two closing parens after $zip[6] ;)
>>
>>
>> regards,
>> 5er
>>
>>
>> PS: No regexes were killed or injured in the production of this message.
>>
>
> Now key in SW1A 1AA as a postcode and see what it does with it.
>
> there is a world beyond north America.
>

I hear ya; Things will only get checked if len=7 and that's 8, so ... .
It's finally coming together for me I think.

Thanks,

Twayne`
  Switch to threaded view of this topic Create a new topic Submit Reply
Previous Topic: Re: korean character sets
Next Topic: Android app Developers requirements
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Wed Dec 11 21:27:28 GMT 2024

Total time taken to generate the page: 0.01805 seconds