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

Susan Sarandon
Release: 2024-10-24 18:31:46
Original
279 people have browsed it

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);
Copy after login

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>
Copy after login

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"]
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template