In this PHP tutorial, you shall learn how to check if given string starts with an uppercase alphabet using preg_match() function, with example programs.

PHP – Check if String Starts with Uppercase

To check if string starts with uppercase/capital letter, perform regular expression match if the first character is uppercase or not.

Provide the regular expression that a string starts with uppercase, and the string as argument to preg_match(). The function shall return true if the string starts with uppercase alphabet, or false if it does not.

Examples

ADVERTISEMENT

1. Check if given string starts with an uppercase alphabet

In this example we will use preg_match() to perform a regular expression match.

The regular expression to check if the first character is uppercase alphabet or not, is

'~^\p{Lu}~u'

We will use this expressing with preg_match() built-in PHP function, to check if the string starts with uppercase. The syntax to use preg_match() for this use case is

preg_match('~^\p{Lu}~u', $string)

The above function call returns true if the string starts with uppercase alphabet, else it returns false.

In the following program, we will take a string “Hello World”, and check if this string starts with uppercase alphabet or not using preg_match().

PHP Program

<?php
$string = "Hello World!";
if ( preg_match('~^\p{Lu}~u', $string) ) {
    echo "\"{$string}\" starts with uppercase.";
} else {
    echo "\"{$string}\" does not start with uppercase.";
}
?>

Output

PHP - Check if String Starts with Uppercase

Conclusion

In this PHP Tutorial, we learned how to check if a string starts with an uppercase alphabet, using PHP built-in function preg_match().