-1

I have a string

 $str="NassarWellerGomez-GarciaSanchez-RenedoLoeches-SanchezGomez-GarciaMunoz-FerrerasSanchez-RenedoChiaoHakkarainenWernerValkamaHarounPlett";

I want to match words starting with capitals only like: Nassar Weller Gomez-Garcia etc

I used this : 

preg_match('/[A-Z][a-z]+/', $str,$match);

But its not working, help me out here please!

Aditya
  • 4,453
  • 3
  • 28
  • 39

2 Answers2

4
preg_match_all('/[A-Z][a-z]*(?:-[A-Z][a-z]*)*/', $str, $match);
var_dump($match[0]);
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • @BarryChapman Thanks, Fixed that. Also now matches `Foo-Bar-Baz` as a single name (any number of hyphenates allowed). – Barmar Dec 31 '12 at 18:48
1

Try this:

$result = preg_split('/[A-Z]/', $str, null, PREG_SPLIT_DELIM_CAPTURE);
var_dump($result);

I haven't tested it, but I think it will work, or at least point you in the right direction.

It does not work for the hyphenated names. For that, I believe you would need to use a (positive or negative) lookbehind, but I don't know enough to explain that off the top of my head. You'll have to look it up, but at least now you know what to look for.


Looking at http://www.regular-expressions.info/lookaround.html as a quick reference, it looks like perhaps this would be the regex with the negative lookbehind you need:

'/(?<!-)[A-Z]/'

This basically means "match any capital letter not followed by a hyphen."

Travesty3
  • 14,351
  • 6
  • 61
  • 98