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
2009-09-23 15:15:49
A:
$first = substr(trim($string), 0, 1);
$is_num = is_numeric($first);
return $is_num;
Evernoob
2009-09-23 15:16:24
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
2009-09-23 15:17:12
It would be nice to get a comment on why my answer got voted down.
Gumbo
2009-09-23 16:05:55
Talk about blatant "strategic downvoting". Sheesh.
John Kugelman
2009-09-23 16:55:54
A:
Try RegEx:
$Line = ...;
preg_match('/^[:space:]*(.)/', $Line, $matches);
$FirstChar = $matches[0];
NawaMan
2009-09-23 15:17:58
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
2009-09-23 15:19:20