简体   繁体   中英

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?

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

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));
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
}
$first = substr(trim($string), 0, 1);
$is_num = is_numeric($first);
return $is_num;

Try RegEx:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM