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

DDD
Release: 2024-10-24 14:06:01
Original
895 people have browsed it

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

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template