fork(1) download
  1. <?php
  2.  
  3. function camelToUS1($string, $us = "-")
  4. {
  5. // insert hyphen between any letter and the beginning of a numeric chain
  6. $string = preg_replace('/([a-z]+)([0-9]+)/i', '$1'.$us.'$2', $string);
  7. // insert hyphen between any lower-to-upper-case letter chain
  8. $string = preg_replace('/([a-z]+)([A-Z]+)/', '$1'.$us.'$2', $string);
  9. // insert hyphen between the end of a numeric chain and the beginning of an alpha chain
  10. $string = preg_replace('/([0-9]+)([a-z]+)/i', '$1'.$us.'$2', $string);
  11.  
  12. // Lowercase
  13. $string = strtolower($string);
  14.  
  15. return $string;
  16. }
  17. function camelToUS2($string, $us = "-") {
  18. '/(?<=\d)(?=[A-Za-z])|(?<=[A-Za-z])(?=\d)|(?<=[a-z])(?=[A-Z])/', $us, $string));
  19. }
  20. function camelToUS3($string, $us = "-") {
  21. return strtolower(preg_replace('/(?<!^)[A-Z]+|(?<!^|\d)[\d]+/', $us.'$0', $string));
  22. }
  23.  
  24. $test_values = [
  25. 'foo' => 'foo',
  26. 'fooBar' => 'foo-bar',
  27. 'foo123' => 'foo-123',
  28. '123Foo' => '123-foo',
  29. 'fooBar123' => 'foo-bar-123',
  30. 'foo123Bar' => 'foo-123-bar',
  31. 'foo123bar' => 'foo-123-bar',
  32. '123FooBar' => '123-foo-bar',
  33. ];
  34.  
  35. echo "OP:\n";
  36. foreach ( $test_values as $key => $val ) {
  37. echo "$key: " . camelToUS1($key) . " => " . (camelToUS1($key) == $val) . "\n";
  38. }
  39. echo "\nanubhava:\n";
  40. foreach ( $test_values as $key => $val ) {
  41. echo "$key: " . camelToUS2($key) . " => " . (camelToUS2($key) == $val) . "\n";
  42. }
  43. echo "\nAdrien Leber:\n";
  44. foreach ( $test_values as $key => $val ) {
  45. echo "$key: " . camelToUS3($key) . " => " . (camelToUS3($key) == $val) . "\n";
  46. }
  47.  
  48. ?>
Success #stdin #stdout 0.01s 52488KB
stdin
Standard input is empty
stdout
OP:
foo: foo => 1
fooBar: foo-bar => 1
foo123: foo-123 => 1
123Foo: 123-foo => 1
fooBar123: foo-bar-123 => 1
foo123Bar: foo-123-bar => 1
foo123bar: foo-123-bar => 1
123FooBar: 123-foo-bar => 1

anubhava:
foo: foo => 1
fooBar: foo-bar => 1
foo123: foo-123 => 1
123Foo: 123-foo => 1
fooBar123: foo-bar-123 => 1
foo123Bar: foo-123-bar => 1
foo123bar: foo-123-bar => 1
123FooBar: 123-foo-bar => 1

Adrien Leber:
foo: foo => 1
fooBar: foo-bar => 1
foo123: foo-123 => 1
123Foo: 123-foo => 1
fooBar123: foo-bar-123 => 1
foo123Bar: foo-123-bar => 1
foo123bar: foo-123bar => 
123FooBar: 123-foo-bar => 1