Project

General

Profile

Download (2.34 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/**
3
 * @file
4
 * String functions.
5
 */
6

    
7
/**
8
 * Truncates a $string to the specified $length.
9
 *
10
 * If the supplied string is equal to or shorter than the $length, the original
11
 * is returned. If an $appendix is defined, the resulting string will have the
12
 * specified $length including the $appendix.
13
 *
14
 * @param string $string
15
 *   The string to truncate.
16
 * @param int $length
17
 *   The maximun length.
18
 * @param string $appendix
19
 *   An optional appendix.
20
 *
21
 * @return string
22
 *   The truncated string.
23
 */
24
function str_trunk(&$string, $length, $appendix = '') {
25
  if (strlen($string) >= $length) {
26
    return substr($string, 0, $length - strlen($appendix)) . $appendix;
27
  }
28
  else {
29
    return $string;
30
  }
31
}
32

    
33
/**
34
 * Checks if a string starts with some substring.
35
 *
36
 * @param string $str
37
 *   The string to test.
38
 * @param string $sub
39
 *   The substring that the string should start with.
40
 *
41
 * @return bool
42
 *   TRUE if the string starts with the substring.
43
 */
44
function str_beginsWith($str, $sub) {
45
  return (substr($str, 0, strlen($sub)) === $sub);
46
}
47

    
48
/**
49
 * Checks if a string ends with some substring.
50
 *
51
 * @param string $str
52
 *   The string to test.
53
 * @param string $sub
54
 *   The substring that the string should end with.
55
 *
56
 * @return bool
57
 *   TRUE if the string ends with the substring.
58
 */
59
function str_endsWith($str, $sub) {
60
  return (substr($str, strlen($str) - strlen($sub)) === $sub);
61
}
62

    
63
/**
64
 * Replaces all keys in an array with the given values.
65
 *
66
 * All occurences in $array of the key defined in $replace_map are replaced
67
 * with the according values in the $replace_map.
68
 *
69
 * @param array $array
70
 *   The array to modify.
71
 * @param array $replace_map
72
 *   The values to replace.
73
 *
74
 * @return array
75
 *   The modified array.
76
 */
77
function array_replace_key($array, $replace_map) {
78
  foreach ($replace_map as $key => $newkey) {
79
    if (isset($array[$key])) {
80
      $array[$newkey] = $array[$key];
81
      unset($array[$key]);
82
    }
83
  }
84
  return $array;
85
}
86

    
87
/**
88
 * Replaces spaces in a string to underscores and returns the string lowercase.
89
 *
90
 * All occurrences of space characters are replaced with an underscore.
91
 * The string is also transformed to lowercase.
92
 *
93
 * @param string $string
94
 *   The string to modify.
95
 *
96
 * @return string
97
 *   The transformed string.
98
 */
99
function generalizeString($string) {
100
  return str_replace(' ', '_', strtolower($string));
101
}
(6-6/9)