-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathStrings.php
More file actions
94 lines (81 loc) · 2.89 KB
/
Strings.php
File metadata and controls
94 lines (81 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
/**
* Defines \TraderInteractive\Util\Strings class.
*/
namespace TraderInteractive\Util;
/**
* Static class with various string functions.
*/
final class Strings
{
/**
* Replaces the format items in a specified string with the string representation of n specified objects.
*
* @param string $format A composit format string
* @param mixed $arguments Variable number of items to format.
*
* @return string Returns a copy of format in which the format items have been
* replaced by the string representations of arg0, arg1,... argN.
*/
public static function format(string $format, string ...$arguments) : string
{
foreach ($arguments as $key => $value) {
$format = str_replace("{{$key}}", (string)$value, $format);
}
return $format;
}
/**
* Checks if $string ends with $suffix and puts the rest of the $string in $nonSuffix.
*
* @param string $string The string to check
* @param string $suffix The suffix to check for
* @param mixed &$nonSuffix This is the part of the string that is not the suffix.
*
* @return bool whether the $string ended with $suffix or not.
*/
public static function endsWith(string $string, string $suffix, &$nonSuffix = null) : bool
{
$suffixLength = strlen($suffix);
if ($suffixLength === 0) {
$nonSuffix = $string;
return true;
}
if (empty($string)) {
$nonSuffix = '';
return false;
}
if (substr_compare($string, $suffix, -$suffixLength, $suffixLength) !== 0) {
$nonSuffix = $string;
return false;
}
$nonSuffix = substr($string, 0, -$suffixLength);
return true;
}
/**
* Truncates the string to the given length, with an ellipsis at the end.
*
* @param string $string The string to shorten.
* @param int $maxLength The length to truncate the string to. The result will not be longer than this, but may be
* shorter.
* @param string $suffix The string to append when truncating. Typically this will be an ellipsis.
*
* @return string The truncated string with the ellipsis included if truncation occured.
*
* @throws \InvalidArgumentException if $maxLength is negative
*/
public static function ellipsize(string $string, int $maxLength, string $suffix = '...') : string
{
if ($maxLength < 0) {
throw new \InvalidArgumentException('$maxLength is negative');
}
if (strlen($string) <= $maxLength) {
return $string;
}
$trimmedLength = $maxLength - strlen($suffix);
$string = substr($string, 0, max(0, $trimmedLength));
if ($string === '') {
return substr($suffix, 0, $maxLength);
}
return $string . $suffix;
}
}