2

我正在尝试从 PHP 中的字符串中检索前几个大写字母,但我不确定是否有特定的函数可以执行此操作。我应该求助于使用正则表达式吗?如果是这样,怎么做?

这是一个应该返回的示例(INPUT => OUTPUT):

ABCD => ABCD
Abcd => A
ABcd => AB
aBCD => empty string ""
abcd => empty string ""

任何帮助,将不胜感激 :)

-克里斯

4

3 回答 3

7

在这种情况下,正则表达式会为您解决问题。试试这个:

preg_match("/^([A-Z]+)/", $input, $matches)

如果返回 true,则您的大写字母应该在 $matches[1] 中。

于 2011-06-29T08:51:30.610 回答
2

我认为你应该使用:

  preg_match('/^[A-Z]+/',$input, $matches);

  $matches[0];//here are your capital 
于 2011-06-29T08:54:37.910 回答
2

尝试:

$input = array(
    'ABCD',
    'Abcd',
    'ABcd',
    'aBCD',
    'abcd',
);

$output = array_map(function ($str) {
    return preg_replace('/^([A-Z]*).*/', '$1', $str);
}, $input);

print_r($output);

输出:

Array
(
    [0] => ABCD
    [1] => A
    [2] => AB
    [3] => 
    [4] => 
)
于 2011-06-29T08:57:17.510 回答