10

I want to split a word by capital letter in PHP

For example:

$string = "facebookPageUrl";

I want it like this:

$array = array("facebook", "Page", "Url");

How should I do it? I want the shortest and most efficient way.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John Smith
  • 203
  • 1
  • 3
  • 11

2 Answers2

17

You can use preg_split with the a look-ahead assertion:

preg_split('/(?=\p{Lu})/u', $str)

Here \p{Lu} is a character class of all Unicode uppercase letters. If you just work with US-ASCII characters, you could also use [A-Z] instead.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Gumbo
  • 643,351
  • 109
  • 780
  • 844
4
$string = "facebookPageUrl";

preg_match_all('((?:^|[A-Z])[^A-Z]*)', $string, $matches);
var_dump($matches);

http://ideone.com/wL9jM

zerkms
  • 249,484
  • 69
  • 436
  • 539