skyzyx
3/6/2012 - 12:45 AM

Inflect between CapitalCase and snake_case

Inflect between CapitalCase and snake_case

<?php

/**
 * Prepare the content for reformatting.
 */
function prep_content($_string)
{
	// Strip all non-alphanumeric characters
	$_string = preg_replace('/[^a-z0-9\-\_\s]/i', '', $_string);

	// FMLCase => FML, Case
	if (preg_match('/([A-Z][A-Z]+)([A-Z][a-z])/', $_string))
	{
		$_string = preg_replace('/([A-Z][A-Z]+)([A-Z][a-z])/', '$1 $2', $_string);
	}

	// camelCase => camel, Case
	if (preg_match('/([a-z])([A-Z])/', $_string))
	{
		$_string = preg_replace('/([a-z])([A-Z])/', '$1 $2', $_string);
	}

	// snake_case => snake, case
	if (preg_match('/([a-z])(_|-|\s+)([a-z])/i', $_string))
	{
		$_string = preg_replace('/([a-z])(_|-|\s+)([a-z])/i', '$1 $3', $_string);
	}

	// Numbers (prepended)
	if (preg_match('/([0-9])([a-z])/i', $_string))
	{
		$_string = preg_replace('/([0-9])([a-z])/i', '$1 $2', $_string);
	}

	// Numbers (appended)
	if (preg_match('/([a-z])([0-9])/i', $_string))
	{
		$_string = preg_replace('/([a-z])([0-9])/i', '$1 $2', $_string);
	}

	// Clean-up and split
	$_string = trim($_string);
	$_string = preg_replace('/\s+/', ' ', $_string);

	return explode(' ', $_string);
}

/**
 * Format the string as CapitalCase (aka, Upper Camel Case, Pascal Case, .NET Case, Studly Case).
 */
public function capitalize($_string)
{
	$_pieces = prep_content($_string);
	$string = implode(' ', $_pieces);
	$string = strtolower($string);
	$string = ucwords($string);

	return str_replace(' ', '', $string);
}

/**
 * Format the string as snake_case (aka, Underscore Case).
 */
public function snakeize($_string)
{
	$_pieces = prep_content($_string);
	$string = implode('_', $_pieces);

	return strtolower($string);
}