1public static function camelCase($str, array $noStrip = [])
2{
3 // non-alpha and non-numeric characters become spaces
4 $str = preg_replace('/[^a-z0-9' . implode("", $noStrip) . ']+/i', ' ', $str);
5 $str = trim($str);
6 // uppercase the first character of each word
7 $str = ucwords($str);
8 $str = str_replace(" ", "", $str);
9 $str = lcfirst($str);
10
11 return $str;
12}
1function from_camel_case($input) {
2 $pattern = '!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!';
3 preg_match_all($pattern, $input, $matches);
4 $ret = $matches[0];
5 foreach ($ret as &$match) {
6 $match = $match == strtoupper($match) ?
7 strtolower($match) :
8 lcfirst($match);
9 }
10 return implode('_', $ret);
11}
12
13// Tests:
14foreach ([
15 'simpleTest' => 'simple_test',
16 'easy' => 'easy',
17 'HTML' => 'html',
18 'simpleXML' => 'simple_xml',
19 'PDFLoad' => 'pdf_load',
20 'startMIDDLELast' => 'start_middle_last',
21 'AString' => 'a_string',
22 'Some4Numbers234' => 'some4_numbers234',
23 'TEST123String' => 'test123_string',
24] as $test => $result) {
25 $output = from_camel_case($test);
26 if ($output === $result) {
27 echo "Pass: $test => $result\n";
28 } else {
29 echo "Fail: $test => $result [$output]\n";
30 }
31}
32/*
33Pass: simpleTest => simple_test
34Pass: easy => easy
35Pass: HTML => html
36Pass: simpleXML => simple_xml
37Pass: PDFLoad => pdf_load
38Pass: startMIDDLELast => start_middle_last
39Pass: AString => a_string
40Pass: Some4Numbers234 => some4_numbers234
41Pass: TEST123String => test123_string
42*/