Joe
Joe

Reputation: 675

How can I get the first non-white space character of a line using php

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?

Upvotes: 1

Views: 5574

Answers (5)

NDM
NDM

Reputation: 6830

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]);

Upvotes: 4

John Kugelman
John Kugelman

Reputation: 361595

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
}

Upvotes: 2

NawaMan
NawaMan

Reputation: 25687

Try RegEx:

$Line = ...;
preg_match('/^[:space:]*(.)/', $Line, $matches);
$FirstChar = $matches[0];

Upvotes: -1

Gumbo
Gumbo

Reputation: 655229

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));

Upvotes: 3

Evernoob
Evernoob

Reputation: 5561

$first = substr(trim($string), 0, 1);
$is_num = is_numeric($first);
return $is_num;

Upvotes: 0

Related Questions