Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a String Starts with a Number in PHP [duplicate]

Possible Duplicate:
Check if a String Ends with a Number in PHP

I'm trying to implement the function below. Would it be best to use some type of regex here? I need to capture the number too.

function startsWithNumber($string) {
  $startsWithNumber = false;

  // Logic

  return $startsWithNumber;
}
like image 781
Kirk Ouimet Avatar asked Nov 06 '10 18:11

Kirk Ouimet


2 Answers

You can use substr and ctype_digit:

function startsWithNumber($string) {
    return strlen($string) > 0 && ctype_digit(substr($string, 0, 1));
}

The additional strlen is just required as ctype_digit returns true for an empty string before PHP 5.1.

Or, if you rather want to use a regular expression:

function startsWithNumber($str) {
    return preg_match('/^\d/', $str) === 1;
}
like image 191
3 revs, 2 users 96% Avatar answered Nov 07 '22 06:11

3 revs, 2 users 96%


Something like to this may work to you:

function str2int($string) {
  $length = strlen($string);   
  for ($i = 0, $int = ''; $i < $length; $i++) {
    if (is_numeric($string[$i]))
        $int .= $string[$i];
     else break;
  }

  return (int) $int;
}
like image 21
Thinker Avatar answered Nov 07 '22 04:11

Thinker