utils.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. /**
  3. * Utility functions for WebBasics library.
  4. *
  5. * @author Taddeus Kroes
  6. * @date 05-10-2012
  7. * @since 0.2
  8. */
  9. namespace webbasics;
  10. /**
  11. * Format a string using parameters in an associative array.
  12. *
  13. * <code>
  14. * echo asprintf('foo %(bar)', array('bar' => 'baz')); // prints 'foo baz'
  15. * </code>
  16. *
  17. * @param string $format The string to format.
  18. * @param array $params An associative array with parameters that are used in $format.
  19. * @package WebBasics
  20. */
  21. function asprintf($format, array $params) {
  22. return preg_replace_callback(
  23. '/%\(([a-z0-9-_ ]*)\)/i',
  24. function($matches) use ($params) {
  25. return (string)$params[$matches[1]];
  26. },
  27. $format
  28. );
  29. }
  30. /**
  31. * Camelize a string.
  32. *
  33. * @param string $string The string to camelize.
  34. * @param bool $upper Whether to make the first character uppercase (defaults to FALSE).
  35. * @return string The camelized string.
  36. */
  37. function camelize($string, $upper=false) {
  38. $camel = preg_replace_callback('/[_ -]([a-z])/', function($matches) {
  39. return strtoupper($matches[1]);
  40. }, $string);
  41. if ($upper)
  42. return ucfirst($camel);
  43. return $camel;
  44. }
  45. ?>