4

I want to get an array of all the words with capital letters that are included in the string. But only if the line begins with "set".

For example:

- string "setUserId", result array("User", "Id")
- string "getUserId", result false

Without limitation about "set" RegEx look like /([A-Z][a-z]+)/

codaddict
  • 445,704
  • 82
  • 492
  • 529
Tui Kiken
  • 205
  • 2
  • 8
  • 1
    You can't do it with a match I think because PCRE doesn't support variable repetition in lookbehinds. Instead use @codaddict solution. – FailedDev Nov 09 '11 at 12:36

1 Answers1

4
$str ='setUserId';                          
$rep_str = preg_replace('/^set/','',$str);
if($str != $rep_str) {
        $array = preg_split('/(?<=[a-z])(?=[A-Z])/',$rep_str);
        var_dump($array);
}

See it

Also your regex will also work.:

$str = 'setUserId';
if(preg_match('/^set/',$str) && preg_match_all('/([A-Z][a-z]*)/',$str,$match)) {
        var_dump($match[1]);                                                    
}

See it

codaddict
  • 445,704
  • 82
  • 492
  • 529
  • Very nice + 1! Is this possible without replace/split i.e. with match? – FailedDev Nov 09 '11 at 12:37
  • A twin regex. Nice. Thanks! I can't give +2 unfortunately :D – FailedDev Nov 09 '11 at 12:51
  • I was hoping that this operation can be performed by one RegEx. – Tui Kiken Nov 09 '11 at 13:03
  • In this case, my version: `$name = 'setUserId'; preg_match_all('/(?:^|[A-Z])[a-z]+/', $name, $matches); $data = $matches[0]; $prefix = array_shift($data); if ($prefix == 'set') { // work with $data containing array('User', 'Id') }` – Tui Kiken Nov 09 '11 at 13:06