开发者

Function to return only the capital letter(s!) at the beginning of a string?

开发者 https://www.devze.com 2023-03-16 16:09 出处:网络
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 reg

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] => 
)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号