我试图从PHP中的字符串中检索前几个大写字母,但我不确定是否有特定的函数可以做到这一点。我应该使用regex吗?如果是,如何?
以下是应该返回的内容的示例(INPUT=>OUTPUT):
ABCD => ABCD
Abcd => A
ABcd => AB
aBCD => empty string ""
abcd => empty string ""
如有任何帮助,我们将不胜感激:)
-Chris
Regex在这种情况下会帮你解决问题。试试这个:
preg_match("/^([A-Z]+)/", $input, $matches)
如果返回true,则大写字母应为$matches[1]。
我认为您应该使用:
preg_match('/^[A-Z]+/',$input, $matches);
$matches[0];//here are your capital
尝试:
$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] =>
)