Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Is the string starting with capital letter (not only in A-Z)?

Tags:

regex

php

How can I check if a string starts with a capital letter, in cases where the first letter might not be in A-Z range but from other languages also AND simultaneously if the first character is not a number?

examples:

"This is string" - match
"this is string" - not match
"5 not good" - not match
"Увеличи starts capital" - match
"мащабиране no capital" - not match

in php:

if (preg_math('/??/i', $str) ) {
  echo 'yeeee haaa';
}
like image 502
faq Avatar asked Dec 01 '22 03:12

faq


1 Answers

Use this regex:

preg_match('#^\p{Lu}#u', $str)

\p{Lu} will match any character that has Unicode character property of uppercase letter.

Demo on regex101 (please ignore the flags m and g, they are for demonstration purpose only)

When you are dealing with a Unicode string (or more specifically, in the case of preg_ functions, the Unicode string must be in UTF-8 encoding), you must always use the u flag to make the engine treat the input string and the pattern with character semantics. Otherwise, by default, preg_ functions treat the pattern and input string as an array of bytes and produce an unexpected result for characters outside the ASCII range.

like image 96
nhahtdh Avatar answered Dec 04 '22 03:12

nhahtdh