Suppose you have this string:
hiThere
What is the fastest way to find where the first upper case character is? (T
in this example)
I am worried about performance as some words are quite long.
Easiest would be to use preg_match (if there is only 1 match) or preg_match_all (if you want all the matches) http://php.net/manual/en/function.preg-match.php
preg_match_all('/[A-Z]/', $str, $matches, PREG_OFFSET_CAPTURE);
Not sure if it is the fastest..
Here's a (more or less) one line solution.
$pos = strcspn($string, 'ABCDEFGHJIJKLMNOPQRSTUVWXYZ');
strcspn will return the position of the first occurrence of any character in the second argument, or the length of the string if no character occurs.
Returns the length of the initial segment of str1 which does not contain any of the characters in str2.
$pos = strcspn($string, 'ABCDEFGHJIJKLMNOPQRSTUVWXYZ');
if ($pos < strlen($string)) {
echo "capital letter as index $pos";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With