简体   繁体   中英

Check that the first character of the string is a digit and there are no letters in the string

How to check that the first character of the string is a digit and there are no letters in the string?

is_int(intval(substr($string, 0, 1))) && !preg_match('\w*}', $string)

This check does not work!

The regex you're looking for is ^[0-9]\P{L}+$ , and you don't need the u flag.

<?php
function check($text) {
    if (($result = preg_match('/^[0-9]\P{L}+$/', $text)) !== false) {
        return $result;
    }
    throw new Exception("Error with regex");
}

check('123')    // true
check('1$%#@')  // true
check('12д54')  // false
check('1łs')    // false
check('')       // false

Also, with open source T-Regx you can do this:

<?php
pattern('^[0-9]\P{L}+$')->test('123');  // true

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