PDA

View Full Version : Quick PHP/RegEx question




yg17
Nov 16, 2006, 12:10 PM
I suck at Regular Expressions. I've got a string that can only have letters in it, so all I need is a little function to return true if if only has letters or false if there's a number in it. Thanks



Zortrium
Nov 16, 2006, 12:36 PM
function checkstring( $stringvar ){
if( preg_match( "/\d/", $stringvar ) )
return false;
return true;
}

If you want to check for ANY non-word characters (ie, punctuation and such), use \W instead of \d (which only checks for digits).

jeremy.king
Nov 16, 2006, 03:08 PM
Not quite.

This should work.


function checkstring( $stringvar ){
return ! preg_match( "/[^a-zA-Z]/", $stringvar )
}

Zortrium
Nov 16, 2006, 04:05 PM
Not quite.

This should work.


function checkstring( $stringvar ){
return ! preg_match( "/[^a-zA-Z]/", $stringvar )
}


How is this any different from what I wrote?

jeremy.king
Nov 16, 2006, 04:18 PM
How is this any different from what I wrote?

First, any combination of letters and punctuation (eg. "test!_()") would return true in your code example since it passes your test of containing digits, but isn't all letters like the OP wanted

If you use \W instead like you suggested following your example, then "test_1234" would also return true since the word character set is comprised of letters, numbers, and underscore ([a-zA-Z_0-9]) - also not what the OP wanted

In my example, letters and ONLY letters are allowed. So cases such as "test1234" or "test()!!" would indeed return false.

Here is a good site to test PHP regular expressions : http://www.solmetra.com/scripts/regex/

yg17
Nov 17, 2006, 11:39 AM
Not quite.

This should work.


function checkstring( $stringvar ){
return ! preg_match( "/[^a-zA-Z]/", $stringvar )
}


Thanks, that works. However, I forgot to mention that it should allow spaces, how would I modify that to accept spaces as well?

jeremy.king
Nov 17, 2006, 12:54 PM
Thanks, that works. However, I forgot to mention that it should allow spaces, how would I modify that to accept spaces as well?

if its just spaces use

[^a-zA-Z ]

or if any whitespace (space, tab, etc)

[^a-zA-Z\s]

savar
Nov 17, 2006, 01:55 PM
Here is a good site to test PHP regular expressions : http://www.solmetra.com/scripts/regex/

It's worth mentioning that regex varies considerably from one engine to another. For instance, PERL regex is very different from the standard grep regex. Java has its own pecularities, and I imagine that PHP does as well.

One of the most common sources of irregularity is what constitutes a special character class like \w. I rarely use them because of that..I'd rather have a portable understanding in my mind that won't break when I move to another platform. So I tend to create character classes explicitly, as kingjr did in his post.