Function to return only the capital letter(s!) at the beginning of a string?
I'm trying to retrieve the first couple of capital letters from a string in PHP, but I'm not sure if there's a specific function to do this. Should I perhaps resort to usin开发者_StackOverflowg regex? If so, how?
Here's an example of what should be returned (INPUT => OUTPUT):
ABCD => ABCD
Abcd => A
ABcd => AB
aBCD => empty string ""
abcd => empty string ""
Any help would be appreciated :)
-Chris
Regex would do the trick for you in this case. Try this:
preg_match("/^([A-Z]+)/", $input, $matches)
If this returns true, your capital letters should be in $matches[1].
I think you should use:
preg_match('/^[A-Z]+/',$input, $matches);
$matches[0];//here are your capital
Try:
$input = array(
'ABCD',
'Abcd',
'ABcd',
'aBCD',
'abcd',
);
$output = array_map(function ($str) {
return preg_replace('/^([A-Z]*).*/', '$1', $str);
}, $input);
print_r($output);
Output:
Array
(
[0] => ABCD
[1] => A
[2] => AB
[3] =>
[4] =>
)
精彩评论