Skip to content

PHP Explode at capital letters?

Last updated on July 10, 2023

In PHP, the explode() function splits a string into an array based on a specified delimiter. By default, it breaks the string at each occurrence of the delimiter. However, you can use a regular expression with the function if you want to split a string at capital letters instead of a specific delimiter.

Here’s an example of how you can use preg_split() to split a string at capital letters:

$string = "ThisIsAString";

// removes whitespace from both sides. 
$string = trim($string);

// Split the string at capital letters
$parts = preg_split('/(?=[A-Z])/', $string);

// Output the result
print_r($parts);

// Output:
Array
(
    [0] => This
    [1] => Is
    [2] => A
    [3] => String
)

In the example above, the regular expression /(?=[A-Z])/ is used as the delimiter for preg_split(). This expression uses a positive lookahead (?=...) to match any position in the string where the next character is an uppercase letter ([A-Z]). This effectively splits the string at each occurrence of a capital letter.

0 0 votes
Article Rating
Subscribe
Notify of
guest

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments