Home  >  Article  >  Backend Development  >  How to Split CamelCase Words into Words with PHP\'s preg_match?

How to Split CamelCase Words into Words with PHP\'s preg_match?

DDD
DDDOriginal
2024-10-24 14:06:01821browse

How to Split CamelCase Words into Words with PHP's preg_match?

Splitting CamelCase Words into Words with PHP's preg_match

In order to split camelCase words into an array of individual words using PHP's preg_match, you can employ the following steps:

The challenge presented was to divide the word "oneTwoThreeFour" into the following array:

['one', 'Two', 'Three', 'Four']

The provided code:

$words = preg_match("/[a-zA-Z]*(?:[a-z][a-zA-Z]*[A-Z]|[A-Z][a-zA-Z]*[a-z])[a-zA-Z]*\b/", $string, $matches)`;

failed to accomplish the desired outcome because it matched the entire word rather than splitting it into individual words.

Solution:

To achieve the desired result, you can utilize preg_split as follows:

$arr = preg_split('/(?=[A-Z])/',$str);

This regex effectively splits the input string just before the uppercase letter. The regex pattern (?=[A-Z]) matches the point immediately preceding an uppercase letter.

Demonstration:

<code class="php">$str = 'oneTwoThreeFour';
$arr = preg_split('/(?=[A-Z])/',$str);

print_r($arr); // Outputs: ['one', 'Two', 'Three', 'Four']</code>

By implementing preg_split with the provided regex pattern, you can accurately divide camelCase words into their individual word components.

The above is the detailed content of How to Split CamelCase Words into Words with PHP\'s preg_match?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn