Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change url slug to camel case

Tags:

regex

php

I have the following string in PHP:

this-is_a-test

I want to change that to this:

thisIsATest

So the string can contain any numer of dashes or underscores. I need some regex function that changes the string to a camel case string.

How can this be done?

like image 927
Vivendi Avatar asked Dec 15 '22 19:12

Vivendi


1 Answers

Use preg_replace_callback:

$string = 'this-is_a-test';

function toUpper($matches) {
  return strtoupper($matches[1]);
}

echo preg_replace_callback('/[-_](.)/', 'toUpper', $string); // thisIsATest

DEMO.

like image 175
João Silva Avatar answered Dec 18 '22 08:12

João Silva