Home  >  Article  >  Backend Development  >  How to Split CamelCase Words into Individual Words in PHP Using Regular Expressions?

How to Split CamelCase Words into Individual Words in PHP Using Regular Expressions?

Susan Sarandon
Susan SarandonOriginal
2024-10-24 18:31:46204browse

How to Split CamelCase Words into Individual Words in PHP Using Regular Expressions?

Splitting CamelCase Words into Words Using PHP preg_match

When working with CamelCase notation, it may be necessary to split the string into individual words. This can be achieved using the preg_match function in PHP.

To split the example word "oneTwoThreeFour", we can utilize the following regular expression:

$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);

However, as you have noted, this expression simply returns the entire word.

Instead, we can use a different approach with preg_split:

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

This expression uses a positive lookahead (?=) to identify the position just before an uppercase letter. By splitting the input string at these points, we obtain the desired result:

["one", "Two", "Three", "Four"]

The above is the detailed content of How to Split CamelCase Words into Individual Words in PHP Using Regular Expressions?. 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