2

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 using 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

Chris
  • 2,905
  • 5
  • 29
  • 30
  • SOLVED - I'd check the accepted answer box, but have to wait 7 more minutes, got to go in 2, I'm sorry. – Chris Jun 29 '11 at 08:58
  • 1
    -1 for not taking the trouble to post proper PHP arrays that others could copy in order to test their answers against. $before, $after. – Cups Jun 29 '11 at 09:04

3 Answers3

7

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].

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 2
    `preg_match("/^[A-Z]+/", $input, $matches)` would do the trick, and store them in `$matches[0]`. Also, [`preg_match`](http://php.net/manual/function.preg-match.php) return value is `1` in case of match, `0` in case of non-match (only relevant in case of doing strict comparison (`===` or `!==`)). – Lumbendil Jun 29 '11 at 08:52
  • Thanks a lot! And, just out of curiosity, what does the rest of the array contain? "$matches[1] will have the text that matched the first captured parenthesized subpattern, and so on." isn't really clear to me (taken from the documentation) :o – Chris Jun 29 '11 at 08:56
2

I think you should use:

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

  $matches[0];//here are your capital 
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
  • Should it be $Matches[0] or $Matches[1] as stated in the top answer? Could just test it out, but might as well get it clear I think :) – Chris Jun 29 '11 at 09:02
2

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] => 
)
Yoshi
  • 54,081
  • 14
  • 89
  • 103
  • +1 for posting a proper PHP array that others could copy and use to check their algos. – Cups Jun 29 '11 at 09:02