Using preg_replace() to convert CamelCase to snake_case

Active3 hr before
Viewed126 times

7 Answers


I have a method now that will convert my camel case strings to snake case, but it's broken into three calls of preg_replace():,I'm wondering if there's a way to reduce my preg_replace() calls to a single line which will give me the same result. Any ideas?, Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers , @urban foo123bar is not camelCase. But you're right there are limits with this regex and it's not the best solution... Something like fooBARFoo will produce foo-barfoo. Anyway, this will for basics camelCase. I edit the answer. Thanks for your feedback ! – JazZ Nov 10 '16 at 11:53

You can use lookarounds to do all this in a single regex:

function camelToUnderscore($string, $us = "-") {
   return strtolower(preg_replace(
      '/(?<=\d)(?=[A-Za-z])|(?<=[A-Za-z])(?=\d)|(?<=[a-z])(?=[A-Z])/', $us, $string));

RegEx Description:

( ? <= \d)( ? = [A - Za - z]) #
if previous position has a digit and next has a letter
   # OR( ? <= [A - Za - z])( ? = \d) #
if previous position has a letter and next has a digit
   # OR( ? <= [a - z])( ? = [A - Z]) #
if previous position has a lowercase and next has a uppercase letter
load more v

function from_camel_case($input) {
   $pattern = '!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!';
   preg_match_all($pattern, $input, $matches);
   $ret = $matches[0];
   foreach($ret as & $match) {
      $match = $match == strtoupper($match) ?
         strtolower($match) :
   return implode('_', $ret);

// Tests:
   'simpleTest' => 'simple_test',
   'easy' => 'easy',
   'HTML' => 'html',
   'simpleXML' => 'simple_xml',
   'PDFLoad' => 'pdf_load',
   'startMIDDLELast' => 'start_middle_last',
   'AString' => 'a_string',
   'Some4Numbers234' => 'some4_numbers234',
   'TEST123String' => 'test123_string',
] as $test => $result) {
   $output = from_camel_case($test);
   if ($output === $result) {
      echo "Pass: $test => $result\n";
   } else {
      echo "Fail: $test => $result [$output]\n";
Pass: simpleTest => simple_test
Pass: easy => easy
Pass: HTML => html
Pass: simpleXML => simple_xml
Pass: PDFLoad => pdf_load
Pass: startMIDDLELast => start_middle_last
Pass: AString => a_string
Pass: Some4Numbers234 => some4_numbers234
Pass: TEST123String => test123_string

You could use preg_replace_callback(), which replaces matches with the result of a function:,I have a string like abc_def_ghi_jkl. I want to replace it to AbcDefGhiJkl. I currently use the following code to change it. Is there a more effective way than this?,Not really pretty, but works well, is in one line and has a better performance than the solution in the question: str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $str))), By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

More effective solution:

str_replace('_', '', ucwords($key, '_'));
load more v

Example #2 ucwords() example with custom delimiter,Example #3 ucwords() example with additional delimiters,Example #1 ucwords() example,mb_convert_case() - Perform case folding on a string

load more v

Given a string in camel case, the task is to write a Java program to convert the given string from camel case to snake case and print the modified string.,The idea is to use the String.replaceAll method to convert given string from camel case to snake case.,Convert camel case string to snake case in Java,Java program to count the occurrence of each character in a string using Hashmap

load more v

The trait_uses_recursive function returns all traits used by a trait:,The pipe method allows you to transform the string by passing its current value to the given callable:,You may provide an integer as a second argument to the function to retrieve the singular or plural form of the string:,The Arr::pluck method retrieves all of the values for a given key from an array:

The Arr::accessible method determines if the given value is array accessible:

use Illuminate\ Support\ Arr;
use Illuminate\ Support\ Collection;

$isAccessible = Arr::accessible(['a' => 1, 'b' => 2]);

// true

$isAccessible = Arr::accessible(new Collection);

// true

$isAccessible = Arr::accessible('abc');

// false

$isAccessible = Arr::accessible(new stdClass);

// false
load more v

Теперь у меня есть метод, который преобразует мои строки camel case в snake case, но он разбит на три вызова preg_replace() : , Сниффер кода для преобразования snake_case в camelCase , Жарко, чтобы сделать jackson использовать snake_case / camelCase по требованию в Spring Boot REST API? , camelCase в snake_case с помощью shell?

Теперь у меня есть метод, который преобразует мои строки camel case в snake case, но он разбит на три вызова preg_replace() :

function camelToUnderscore($string, $us = "-") {
   // insert hyphen between any letter and the beginning of a numeric chain
   $string = preg_replace('/([a-z]+)([0-9]+)/i', '$1'.$us.
      '$2', $string);
   // insert hyphen between any lower-to-upper-case letter chain
   $string = preg_replace('/([a-z]+)([A-Z]+)/', '$1'.$us.
      '$2', $string);
   // insert hyphen between the end of a numeric chain and the beginning of an alpha chain
   $string = preg_replace('/([0-9]+)([a-z]+)/i', '$1'.$us.
      '$2', $string);

   // Lowercase
   $string = strtolower($string);

   return $string;

Я написал тесты, чтобы проверить его точность, и он правильно работает со следующим массивом входных данных (array('input' => 'output') ):

$test_values = [
   'foo' => 'foo',
   'fooBar' => 'foo-bar',
   'foo123' => 'foo-123',
   '123Foo' => '123-foo',
   'fooBar123' => 'foo-bar-123',
   'foo123Bar' => 'foo-123-bar',
   '123FooBar' => '123-foo-bar',
load more v

Other "using-undefined" queries related to "Using preg_replace() to convert CamelCase to snake_case"