Page 1 of 1

Returning the Value of a part of a variable (solved)

Posted: Mon Jun 19, 2006 12:21 pm
by Bigun
I'd like to have PHP look over the 1st character of a variable, then be able to determine if it is a number or a letter. How would that code look?

Posted: Mon Jun 19, 2006 12:31 pm
by Bigun
It returns the variable type, but not the character type.

I would like to distinguish the difference between:

"B-11234"

and

"11234"

I'm trying to detect if the first character in the variable is a letter... specifically "B".

Posted: Mon Jun 19, 2006 12:34 pm
by Benjamin

Code: Select all

function FirstCharacterIsLetter($String) {
  $String = substr($String, 0, 1);
  $String = strtolower($String);
  $Letters = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
  if (!in_array($String,$Letters)) {
    return false;
  } else {
    return true;
  }
}

Posted: Mon Jun 19, 2006 1:06 pm
by Weirdan

Code: Select all

function firstCharIsLetter($string) {
  return ereg('^[[:alpha:]]', $string);
}

Posted: Mon Jun 19, 2006 1:09 pm
by Benjamin
I like that one better :wink:

Posted: Mon Jun 19, 2006 1:16 pm
by Weirdan
Geshi eats character classes like this: [[:alpha:]]

Posted: Mon Jun 19, 2006 2:09 pm
by Bigun
Worked like a charm, thanks...

Posted: Mon Jun 19, 2006 2:26 pm
by John Cartwright
astions wrote:

Code: Select all

function FirstCharacterIsLetter($String) {
  $String = substr($String, 0, 1);
  $String = strtolower($String);
  $Letters = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
  if (!in_array($String,$Letters)) {
    return false;
  } else {
    return true;
  }
}
I think you'll make use of the range() function ;)

Posted: Mon Jun 19, 2006 2:29 pm
by Benjamin
range() returns an array of elements from low to high, inclusive. If low > high, the sequence will be from high to low.
I dig it. Thanks!