Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

yg17

macrumors Pentium
Original poster
Aug 1, 2004
15,028
3,003
St. Louis, MO
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

macrumors 6502
Jun 23, 2003
461
0
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

macrumors 603
Jul 23, 2002
5,479
1
Holly Springs, NC
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

macrumors Pentium
Original poster
Aug 1, 2004
15,028
3,003
St. Louis, MO
Not quite.

This should work.

PHP:
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?
 

savar

macrumors 68000
Jun 6, 2003
1,950
0
District of Columbia
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.