tags:

views:

247

answers:

5

I have a line that typically starts with a few spaces as the lines are in columns and use a monospace font to make things line up. I want to check if the first non-white space character (or even just the first thing that isn't a space) and see if that is a number. What is the least server intensive way of doing this?

+1  A: 

You can use trim(), (or ltrim() in this case to delete the whitespace, and make use of the array access of strings:

$line = ltrim($line);
is_numeric($line[0]);
Nicky De Maeyer
A: 
$first = substr(trim($string), 0, 1);
$is_num = is_numeric($first);
return $is_num;
Evernoob
A: 

You can use a regular expression:

if (preg_match('/^\s*(\S)/m', $line, $match)) {
    var_dump($match[0]);
}

Or you remove any whitespace at the begin and then get the first character:

$line_clean = ltrim($line);
var_dump(substr($line_clean, 0, 1));
Gumbo
It would be nice to get a comment on why my answer got voted down.
Gumbo
Talk about blatant "strategic downvoting". Sheesh.
John Kugelman
A: 

Try RegEx:

$Line = ...;
preg_match('/^[:space:]*(.)/', $Line, $matches);
$FirstChar = $matches[0];
NawaMan
A: 
if (preg_match('/^\s*\d/', $line)) {
    // ^    starting at the beginning of the line
    // \s*  look for zero or more whitespace characters
    // \d   and then a digit
}
John Kugelman