simPod
simPod

Reputation: 13466

php separate string by capitals

I have for example this string: "iCanSeeBluePeople" and I need it to separate it into array by capital letters and the first word which starts with lowercase so I would recieve array like ["i","Can","See","Blue","People"]

The strings can be like "grandPrix2009" => ["grand","Prix","2009"], "dog" => ["dog"], "aDog" => ["a","Dog"] and so on

I found this code which works fine but I doesn't apply to numbers and ignores the fist lowercase letter:

<?
$str="MustangBlueHeadlining";

preg_match_all('/[A-Z][^A-Z]*/',$str,$results);
?>

Thanks for help

Upvotes: 2

Views: 109

Answers (1)

sch
sch

Reputation: 27506

You can use the regex /[a-z]+|[A-Z]+[a-z]*|[0-9]+/.

<?
    $str="thisIsATestVariableNumber000";
    preg_match_all('/[a-z]+|[A-Z]+[a-z]*|[0-9]+/',$str,$results);
    print_r($results);
?>

Result:

Array
(
    [0] => Array
    (
        [0] => this
        [1] => Is
        [2] => ATest
        [3] => Variable
        [4] => Number
        [5] => 000
    )

)

Use /[a-z]+|[A-Z][a-z]*|[0-9]+/ if you want ATest to be separated into A and Test.

<?
    $str="thisIsATestVariableNumber000";
    preg_match_all('/[a-z]+|[A-Z][a-z]*|[0-9]+/',$str,$results);
    print_r($results);
?>

Result:

Array
(
    [0] => Array
    (
        [0] => this
        [1] => Is
        [2] => A
        [3] => Test
        [4] => Variable
        [5] => Number
        [6] => 000
    )

)

Upvotes: 3

Related Questions