[regex] camelCase to normal text

Associate
Joined
21 May 2003
Posts
1,365
I need to convert a string in camel case to normal text, i.e.

"thisIsAString" to "this is a string"

using PHP and preg_replace but I'm stumped, any ideas?

PHP:
$text = "thisIsAString";

$text = unCamelize($text);

function unCamelize($text)
{
  $pattern = '([A-Z])';
  $replace = '$1';
  $text = strtolower(preg_replace($pattern, $replace, $text));
  
  return $text;
}
 
Besides the point, surely just use strtolower() on its own? Because that's effectively all that the function is doing.
 
i initially thought preg_replace("/(.)([A-Z])/e","'$1'.strtolower('$2')","thisIsAString"); would work, but it doesn't catch the 'A' because its already evaluated as part of another substitution :(

this works :

PHP:
strtolower(preg_replace("/([A-Z])([A-Z])/","$1 $2",
preg_replace("/(.)([A-Z])/","$1 $2","thisIsAString")));
 
I'd probably do it like:

PHP:
$string = "thisIsAStringOr2";
 $string = preg_replace('|([A-Z0-9]{1})|e', "strtolower(' \\1')", $string);
 // this is a string or 2

Should work. Or if you want to protect proper-casing, in the instance your camelCase is within a proper sentence, the following should also work (could probably be improved a great deal)...

PHP:
$string = "Hello World, do you like my camelCase? thisIsAString";
 $string = preg_replace('|([^\s])([A-Z]{1})?([A-Z]{1})|e', "strtolower(str_replace('  ', ' ', '\\1 \\2 \\3'))", $string);
 // Hello World, do you like my camel case? this is a string
 
Back
Top Bottom