查找字符串中第一个大写字符的最快方法

Mar*_*tin 8 php string character uppercase

假设你有这个字符串:

hiThere

查找第一个大写字符的最快方法是什么?(T在这个例子中)

我担心表现,因为有些词很长.

cra*_*ton 20

最简单的方法是使用preg_match(如果只有1个匹配)或preg_match_all(如果你想要所有的匹配) http://php.net/manual/en/function.preg-match.php

preg_match_all('/[A-Z]/', $str, $matches, PREG_OFFSET_CAPTURE);
Run Code Online (Sandbox Code Playgroud)

不确定它是否是最快的..


Sam*_*son 6

为了找到第一个大写字符,我会使用以下PREG_OFFSET_CAPTURE标志preg_match:

$string = "hiThere";

preg_match( '/[A-Z]/', $string, $matches, PREG_OFFSET_CAPTURE );

print_r( $matches[0] );
Run Code Online (Sandbox Code Playgroud)

返回以下内容:

Array ( [0] => T [1] => 2 )
Run Code Online (Sandbox Code Playgroud)

您可以将此逻辑包装到函数中并反复使用它:

function firstUC ( $subject ) {
  $n = preg_match( '/[A-Z]/', $subject, $matches, PREG_OFFSET_CAPTURE );
  return $n ? $matches[0] : false;
}

echo ( $res = firstUC( "upperCase" ) ) ? $res[1] : "Not found" ;
// Returns: 5

echo ( $res = firstUC( "nouppers!" ) ) ? $res[1] : "Not found" ;
// Returns: Not found
Run Code Online (Sandbox Code Playgroud)


小智 6

其他做法

$stringCamelCase = 'stringCamelCase';// hiThere
Run Code Online (Sandbox Code Playgroud)

与preg_split()的方式:

$array      = preg_split('#([A-Z][^A-Z]*)#', $stringCamelCase, null, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
echo strlen($array[0]);// $array = ['string', 'Camel', 'Case']
Run Code Online (Sandbox Code Playgroud)

用strpbrk()方式:

$CamelCase = strpbrk($stringCamelCase, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
echo strpos($stringCamelCase, $CamelCase);
Run Code Online (Sandbox Code Playgroud)