Page 1 of 1

Split a String On Capital Letters

Posted: Mon May 10, 2010 10:05 am
by N1gel
Hi

I'm trying to split a sting on capital letters. I'm sure I could do it with a loop through each character and gettting the ASCII value but I was thinking there might be a simple way to do it with preg_split. However I'm not very experienced with Regular Expressions.

Can anybody help?

As an example I'm trying to split the Text "RegularExpression" to an array like Array([0]=>Regular [1]=>Expression)

Code: Select all

print_r(preg_split("[A-Z]","RegularExpression"));
Also If anybody knows of a good place for notes on Regular Expressions that would be great

Thanks

Nigel

Re: Split a String On Capital Letters

Posted: Mon May 10, 2010 10:40 am
by mikosiko
http://www.addedbytes.com/cheat-sheets/ ... version-1/

and be sure to read version 2 too....

you can try also this approach:

Code: Select all

$astr = preg_split('/([A-Z])/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($astr);
NOTE: Edited before see AbraCadaver's post....

Re: Split a String On Capital Letters

Posted: Mon May 10, 2010 10:40 am
by AbraCadaver
If you add delimiters to your expression "/[A-Z]/" it will work, unfortunately you lose the capital letters. preg_split() won't work here, but you can return an array of matches like:

Code: Select all

preg_match_all("/[A-Z][^A-Z]*/", "RegularExpression", $matches);
print_r($matches);
This may need to be tweaked depending on how you want to handle spaces, numbers, consecutive caps etc...

I use: http://www.regular-expressions.info

Re: Split a String On Capital Letters

Posted: Mon May 10, 2010 11:16 am
by AbraCadaver
mikosiko wrote:http://www.addedbytes.com/cheat-sheets/ ... version-1/

and be sure to read version 2 too....

you can try also this approach:

Code: Select all

$astr = preg_split('/([A-Z])/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
print_r($astr);
NOTE: Edited before see AbraCadaver's post....
As I said, preg_split() doesn't work as needed:
[text]Array
(
[0] =>
[1] => R
[2] => egular
[3] => E
[4] => xpression
)[/text]

Re: Split a String On Capital Letters

Posted: Mon May 10, 2010 11:34 am
by mikosiko
NOTE: Edited before see AbraCadaver's post....
I was agreeing with you :wink: