Home > Backend Development > PHP Tutorial > How to Split CamelCase Words with preg_match in PHP?

How to Split CamelCase Words with preg_match in PHP?

Barbara Streisand
Release: 2024-10-25 04:36:02
Original
1038 people have browsed it

How to Split CamelCase Words with preg_match in PHP?

Splitting CamelCase Words with preg_match in PHP

To dissect camelCase words into their component parts using preg_match, a different approach is required than the one you initially employed. Here's how to achieve the desired result:

Updated Regular Expression:

<code class="php">$pattern = '/(?=[A-Z])/';</code>
Copy after login

Using preg_split:

Utilize the preg_split function, which splits a string based on a pattern, as follows:

<code class="php">$arr = preg_split($pattern, $str);</code>
Copy after login

Explanation:

The regular expression (?=[A-Z]) identifies every position immediately preceding an uppercase letter. By doing this, we effectively establish split points within the camelCase word.

Example:

Suppose you have the camelCase word "oneTwoThreeFour" stored in a variable named $str. Running the above code will yield the following result:

<code class="php">print_r($arr); // Output: Array ( [0] => one [1] => Two [2] => Three [3] => Four )</code>
Copy after login

This accurately separates the word into its intended components.

The above is the detailed content of How to Split CamelCase Words with preg_match in PHP?. 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