1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Core\Traits; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* a trait with some string related helpers |
7
|
|
|
* Trait StringFunctions |
8
|
|
|
* @package Core\Traits |
9
|
|
|
*/ |
10
|
|
|
trait StringFunctions |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* does a haystack start with a needle ? |
14
|
|
|
* @param $haystack string the string to search in |
15
|
|
|
* @param $needle string the string to search for |
16
|
|
|
* @return bool |
17
|
|
|
*/ |
18
|
|
|
public function startsWith(string $haystack, string $needle): bool |
19
|
|
|
{ |
20
|
|
|
$length = strlen($needle); |
21
|
|
|
return (substr($haystack, 0, $length) === $needle); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Does a haystack end with a needle |
26
|
|
|
* @param $haystack string the string to search in |
27
|
|
|
* @param $needle string the string to search for |
28
|
|
|
* @return bool |
29
|
|
|
*/ |
30
|
|
|
public function endsWith(string $haystack, string $needle): bool |
31
|
|
|
{ |
32
|
|
|
$length = strlen($needle); |
33
|
|
|
if ($length == 0) { |
34
|
|
|
return true; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
return (substr($haystack, -$length) === $needle); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Remove the tail of a string |
42
|
|
|
* @param $string string to slice apart |
43
|
|
|
* @param $tail string the string to remove |
44
|
|
|
* @return string |
45
|
|
|
*/ |
46
|
|
|
public function removeFromEnd(string $string, string $tail): string |
47
|
|
|
{ |
48
|
|
|
if ($this->endsWith($string, $tail)) { |
49
|
|
|
$string = substr($string, 0, -strlen($tail)); |
50
|
|
|
} |
51
|
|
|
return $string; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* remove some characters from the front of the string |
56
|
|
|
* @param string $string the string to be decapitated |
57
|
|
|
* @param string $head the head to be cut off ("OFF WITH HIS HEAD") |
58
|
|
|
* @return string |
59
|
|
|
*/ |
60
|
|
|
public function removeFromBeginning(string $string, string $head): string |
61
|
|
|
{ |
62
|
|
|
if ($this->startsWith($string, $head)) { |
63
|
|
|
$string = substr($string, strlen($head)); |
64
|
|
|
} |
65
|
|
|
return $string; |
66
|
|
|
} |
67
|
|
|
} |