Nedim
Nedim

Reputation: 573

Check if string contains only lowercase letters and underscores

I would like to check if a given string contains only lowercase letters and underscores. It may not contain whitespaces, numbers, uppercase letters, or special symbols/characters.

One extra rule: no accented/multibyte letters like ä, ö, etc.

Upvotes: 1

Views: 3052

Answers (2)

mickmackusa
mickmackusa

Reputation: 47883

You can use preg_match() or a non-regex approach that removes all whitelisted characters and checks if any characters are leftover.

Code: (Demo)

$strings = [
    'my_name_is_John_Doe',
    'my_name_is john doe',
    'my_name_is_john_doe',
    'i_am_20_years_old',
    "i'm_cool!"
];

foreach ($strings as $string) {
    echo json_encode([
             $string,
             !strlen(ltrim($string, 'a..z_')),
             !preg_match('/[a-z_]*[^a-z_]/', $string)
         ]);
    echo "\n\n";
}

Output:

["my_name_is_John_Doe",false,false]

["my_name_is john doe",false,false]

["my_name_is_john_doe",true,true]

["i_am_20_years_old",false,false]

["i'm_cool!",false,false]

In terms of step performance, here is a table of working patterns for each provided sample string:

string match
/^[a-z_]+$/
don't match
/[^a-z_]/
don't match
/.*[^a-z_]/
don't match
/[a-z_]*[^a-z_]/
my_name_is_John_Doe 13 13 6 3
my_name_is john doe 12 12 7 3
my_name_is_john_doe 4 20 23 40
i_am_20_years_old 7 7 14 3
i'm_cool! 3 3 4 3

The above table is purely an academic offering. On input strings of such small size, any performance gains or losses will be indistinguishable to human end users. In other words, this task is highly unlikely to be the performance bottleneck for your application, so choose a technique that you understand and can maintain.

Upvotes: 0

Jawad Sharif
Jawad Sharif

Reputation: 90

you can simply use:

/^[a-z_]+$/

For description and more examples you can visit here

Upvotes: 5

Related Questions